babylon.viewer.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229
  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. "use strict";
  113. var BABYLON;
  114. (function (BABYLON) {
  115. /**
  116. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  117. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  118. */
  119. var EffectFallbacks = /** @class */ (function () {
  120. function EffectFallbacks() {
  121. this._defines = {};
  122. this._currentRank = 32;
  123. this._maxRank = -1;
  124. }
  125. /**
  126. * Removes the fallback from the bound mesh.
  127. */
  128. EffectFallbacks.prototype.unBindMesh = function () {
  129. this._mesh = null;
  130. };
  131. /**
  132. * Adds a fallback on the specified property.
  133. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  134. * @param define The name of the define in the shader
  135. */
  136. EffectFallbacks.prototype.addFallback = function (rank, define) {
  137. if (!this._defines[rank]) {
  138. if (rank < this._currentRank) {
  139. this._currentRank = rank;
  140. }
  141. if (rank > this._maxRank) {
  142. this._maxRank = rank;
  143. }
  144. this._defines[rank] = new Array();
  145. }
  146. this._defines[rank].push(define);
  147. };
  148. /**
  149. * Sets the mesh to use CPU skinning when needing to fallback.
  150. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  151. * @param mesh The mesh to use the fallbacks.
  152. */
  153. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  154. this._mesh = mesh;
  155. if (rank < this._currentRank) {
  156. this._currentRank = rank;
  157. }
  158. if (rank > this._maxRank) {
  159. this._maxRank = rank;
  160. }
  161. };
  162. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  163. /**
  164. * Checks to see if more fallbacks are still availible.
  165. */
  166. get: function () {
  167. return this._currentRank <= this._maxRank;
  168. },
  169. enumerable: true,
  170. configurable: true
  171. });
  172. /**
  173. * Removes the defines that shoould be removed when falling back.
  174. * @param currentDefines defines the current define statements for the shader.
  175. * @param effect defines the current effect we try to compile
  176. * @returns The resulting defines with defines of the current rank removed.
  177. */
  178. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  179. // First we try to switch to CPU skinning
  180. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  181. this._mesh.computeBonesUsingShaders = false;
  182. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. this._uniformBuffersNames = {};
  272. this._isReady = false;
  273. this._compilationError = "";
  274. this.name = baseName;
  275. if (attributesNamesOrOptions.attributes) {
  276. var options = attributesNamesOrOptions;
  277. this._engine = uniformsNamesOrEngine;
  278. this._attributesNames = options.attributes;
  279. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  280. this._samplers = options.samplers.slice();
  281. this.defines = options.defines;
  282. this.onError = options.onError;
  283. this.onCompiled = options.onCompiled;
  284. this._fallbacks = options.fallbacks;
  285. this._indexParameters = options.indexParameters;
  286. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  287. if (options.uniformBuffersNames) {
  288. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  289. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  290. }
  291. }
  292. }
  293. else {
  294. this._engine = engine;
  295. this.defines = defines;
  296. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  297. this._samplers = samplers ? samplers.slice() : [];
  298. this._attributesNames = attributesNamesOrOptions;
  299. this.onError = onError;
  300. this.onCompiled = onCompiled;
  301. this._indexParameters = indexParameters;
  302. this._fallbacks = fallbacks;
  303. }
  304. this.uniqueId = Effect._uniqueIdSeed++;
  305. var vertexSource;
  306. var fragmentSource;
  307. if (baseName.vertexElement) {
  308. vertexSource = document.getElementById(baseName.vertexElement);
  309. if (!vertexSource) {
  310. vertexSource = baseName.vertexElement;
  311. }
  312. }
  313. else {
  314. vertexSource = baseName.vertex || baseName;
  315. }
  316. if (baseName.fragmentElement) {
  317. fragmentSource = document.getElementById(baseName.fragmentElement);
  318. if (!fragmentSource) {
  319. fragmentSource = baseName.fragmentElement;
  320. }
  321. }
  322. else {
  323. fragmentSource = baseName.fragment || baseName;
  324. }
  325. this._loadVertexShader(vertexSource, function (vertexCode) {
  326. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  327. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  328. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  329. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  330. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  331. if (baseName) {
  332. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  333. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  334. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  335. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  336. }
  337. else {
  338. _this._vertexSourceCode = migratedVertexCode;
  339. _this._fragmentSourceCode = migratedFragmentCode;
  340. }
  341. _this._prepareEffect();
  342. });
  343. });
  344. });
  345. });
  346. });
  347. });
  348. }
  349. Object.defineProperty(Effect.prototype, "key", {
  350. /**
  351. * Unique key for this effect
  352. */
  353. get: function () {
  354. return this._key;
  355. },
  356. enumerable: true,
  357. configurable: true
  358. });
  359. /**
  360. * If the effect has been compiled and prepared.
  361. * @returns if the effect is compiled and prepared.
  362. */
  363. Effect.prototype.isReady = function () {
  364. return this._isReady;
  365. };
  366. /**
  367. * The engine the effect was initialized with.
  368. * @returns the engine.
  369. */
  370. Effect.prototype.getEngine = function () {
  371. return this._engine;
  372. };
  373. /**
  374. * The compiled webGL program for the effect
  375. * @returns the webGL program.
  376. */
  377. Effect.prototype.getProgram = function () {
  378. return this._program;
  379. };
  380. /**
  381. * The set of names of attribute variables for the shader.
  382. * @returns An array of attribute names.
  383. */
  384. Effect.prototype.getAttributesNames = function () {
  385. return this._attributesNames;
  386. };
  387. /**
  388. * Returns the attribute at the given index.
  389. * @param index The index of the attribute.
  390. * @returns The location of the attribute.
  391. */
  392. Effect.prototype.getAttributeLocation = function (index) {
  393. return this._attributes[index];
  394. };
  395. /**
  396. * Returns the attribute based on the name of the variable.
  397. * @param name of the attribute to look up.
  398. * @returns the attribute location.
  399. */
  400. Effect.prototype.getAttributeLocationByName = function (name) {
  401. var index = this._attributesNames.indexOf(name);
  402. return this._attributes[index];
  403. };
  404. /**
  405. * The number of attributes.
  406. * @returns the numnber of attributes.
  407. */
  408. Effect.prototype.getAttributesCount = function () {
  409. return this._attributes.length;
  410. };
  411. /**
  412. * Gets the index of a uniform variable.
  413. * @param uniformName of the uniform to look up.
  414. * @returns the index.
  415. */
  416. Effect.prototype.getUniformIndex = function (uniformName) {
  417. return this._uniformsNames.indexOf(uniformName);
  418. };
  419. /**
  420. * Returns the attribute based on the name of the variable.
  421. * @param uniformName of the uniform to look up.
  422. * @returns the location of the uniform.
  423. */
  424. Effect.prototype.getUniform = function (uniformName) {
  425. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  426. };
  427. /**
  428. * Returns an array of sampler variable names
  429. * @returns The array of sampler variable neames.
  430. */
  431. Effect.prototype.getSamplers = function () {
  432. return this._samplers;
  433. };
  434. /**
  435. * The error from the last compilation.
  436. * @returns the error string.
  437. */
  438. Effect.prototype.getCompilationError = function () {
  439. return this._compilationError;
  440. };
  441. /**
  442. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  443. * @param func The callback to be used.
  444. */
  445. Effect.prototype.executeWhenCompiled = function (func) {
  446. if (this.isReady()) {
  447. func(this);
  448. return;
  449. }
  450. this.onCompileObservable.add(function (effect) {
  451. func(effect);
  452. });
  453. };
  454. /** @ignore */
  455. Effect.prototype._loadVertexShader = function (vertex, callback) {
  456. if (BABYLON.Tools.IsWindowObjectExist()) {
  457. // DOM element ?
  458. if (vertex instanceof HTMLElement) {
  459. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  460. callback(vertexCode);
  461. return;
  462. }
  463. }
  464. // Base64 encoded ?
  465. if (vertex.substr(0, 7) === "base64:") {
  466. var vertexBinary = window.atob(vertex.substr(7));
  467. callback(vertexBinary);
  468. return;
  469. }
  470. // Is in local store ?
  471. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  472. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  473. return;
  474. }
  475. var vertexShaderUrl;
  476. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  477. vertexShaderUrl = vertex;
  478. }
  479. else {
  480. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  481. }
  482. // Vertex shader
  483. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  484. };
  485. /** @ignore */
  486. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  487. if (BABYLON.Tools.IsWindowObjectExist()) {
  488. // DOM element ?
  489. if (fragment instanceof HTMLElement) {
  490. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  491. callback(fragmentCode);
  492. return;
  493. }
  494. }
  495. // Base64 encoded ?
  496. if (fragment.substr(0, 7) === "base64:") {
  497. var fragmentBinary = window.atob(fragment.substr(7));
  498. callback(fragmentBinary);
  499. return;
  500. }
  501. // Is in local store ?
  502. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  503. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  504. return;
  505. }
  506. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  507. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  508. return;
  509. }
  510. var fragmentShaderUrl;
  511. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  512. fragmentShaderUrl = fragment;
  513. }
  514. else {
  515. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  516. }
  517. // Fragment shader
  518. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  519. };
  520. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  521. // Rebuild shaders source code
  522. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  523. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  524. vertexCode = prefix + vertexCode;
  525. fragmentCode = prefix + fragmentCode;
  526. // Number lines of shaders source code
  527. var i = 2;
  528. var regex = /\n/gm;
  529. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  530. i = 2;
  531. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. // Dump shaders name and formatted source code
  533. if (this.name.vertexElement) {
  534. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  535. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  536. }
  537. else if (this.name.vertex) {
  538. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  539. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  540. }
  541. else {
  542. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  543. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  544. }
  545. };
  546. ;
  547. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  548. var preparedSourceCode = this._processPrecision(sourceCode);
  549. if (this._engine.webGLVersion == 1) {
  550. callback(preparedSourceCode);
  551. return;
  552. }
  553. // Already converted
  554. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  555. callback(preparedSourceCode.replace("#version 300 es", ""));
  556. return;
  557. }
  558. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  559. // Remove extensions
  560. // #extension GL_OES_standard_derivatives : enable
  561. // #extension GL_EXT_shader_texture_lod : enable
  562. // #extension GL_EXT_frag_depth : enable
  563. // #extension GL_EXT_draw_buffers : require
  564. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  565. var result = preparedSourceCode.replace(regex, "");
  566. // Migrate to GLSL v300
  567. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  568. result = result.replace(/attribute[ \t]/g, "in ");
  569. result = result.replace(/[ \t]attribute/g, " in");
  570. if (isFragment) {
  571. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  572. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  573. result = result.replace(/texture2D\s*\(/g, "texture(");
  574. result = result.replace(/textureCube\s*\(/g, "texture(");
  575. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  576. result = result.replace(/gl_FragColor/g, "glFragColor");
  577. result = result.replace(/gl_FragData/g, "glFragData");
  578. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  579. }
  580. callback(result);
  581. };
  582. Effect.prototype._processIncludes = function (sourceCode, callback) {
  583. var _this = this;
  584. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  585. var match = regex.exec(sourceCode);
  586. var returnValue = new String(sourceCode);
  587. while (match != null) {
  588. var includeFile = match[1];
  589. // Uniform declaration
  590. if (includeFile.indexOf("__decl__") !== -1) {
  591. includeFile = includeFile.replace(/__decl__/, "");
  592. if (this._engine.supportsUniformBuffers) {
  593. includeFile = includeFile.replace(/Vertex/, "Ubo");
  594. includeFile = includeFile.replace(/Fragment/, "Ubo");
  595. }
  596. includeFile = includeFile + "Declaration";
  597. }
  598. if (Effect.IncludesShadersStore[includeFile]) {
  599. // Substitution
  600. var includeContent = Effect.IncludesShadersStore[includeFile];
  601. if (match[2]) {
  602. var splits = match[3].split(",");
  603. for (var index = 0; index < splits.length; index += 2) {
  604. var source = new RegExp(splits[index], "g");
  605. var dest = splits[index + 1];
  606. includeContent = includeContent.replace(source, dest);
  607. }
  608. }
  609. if (match[4]) {
  610. var indexString = match[5];
  611. if (indexString.indexOf("..") !== -1) {
  612. var indexSplits = indexString.split("..");
  613. var minIndex = parseInt(indexSplits[0]);
  614. var maxIndex = parseInt(indexSplits[1]);
  615. var sourceIncludeContent = includeContent.slice(0);
  616. includeContent = "";
  617. if (isNaN(maxIndex)) {
  618. maxIndex = this._indexParameters[indexSplits[1]];
  619. }
  620. for (var i = minIndex; i < maxIndex; i++) {
  621. if (!this._engine.supportsUniformBuffers) {
  622. // Ubo replacement
  623. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  624. return p1 + "{X}";
  625. });
  626. }
  627. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  628. }
  629. }
  630. else {
  631. if (!this._engine.supportsUniformBuffers) {
  632. // Ubo replacement
  633. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  634. return p1 + "{X}";
  635. });
  636. }
  637. includeContent = includeContent.replace(/\{X\}/g, indexString);
  638. }
  639. }
  640. // Replace
  641. returnValue = returnValue.replace(match[0], includeContent);
  642. }
  643. else {
  644. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  645. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  646. Effect.IncludesShadersStore[includeFile] = fileContent;
  647. _this._processIncludes(returnValue, callback);
  648. });
  649. return;
  650. }
  651. match = regex.exec(sourceCode);
  652. }
  653. callback(returnValue);
  654. };
  655. Effect.prototype._processPrecision = function (source) {
  656. if (source.indexOf("precision highp float") === -1) {
  657. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  658. source = "precision mediump float;\n" + source;
  659. }
  660. else {
  661. source = "precision highp float;\n" + source;
  662. }
  663. }
  664. else {
  665. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  666. source = source.replace("precision highp float", "precision mediump float");
  667. }
  668. }
  669. return source;
  670. };
  671. /**
  672. * Recompiles the webGL program
  673. * @param vertexSourceCode The source code for the vertex shader.
  674. * @param fragmentSourceCode The source code for the fragment shader.
  675. * @param onCompiled Callback called when completed.
  676. * @param onError Callback called on error.
  677. */
  678. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  679. var _this = this;
  680. this._isReady = false;
  681. this._vertexSourceCodeOverride = vertexSourceCode;
  682. this._fragmentSourceCodeOverride = fragmentSourceCode;
  683. this.onError = function (effect, error) {
  684. if (onError) {
  685. onError(error);
  686. }
  687. };
  688. this.onCompiled = function () {
  689. var scenes = _this.getEngine().scenes;
  690. for (var i = 0; i < scenes.length; i++) {
  691. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  692. }
  693. if (onCompiled) {
  694. onCompiled(_this._program);
  695. }
  696. };
  697. this._fallbacks = null;
  698. this._prepareEffect();
  699. };
  700. /**
  701. * Gets the uniform locations of the the specified variable names
  702. * @param names THe names of the variables to lookup.
  703. * @returns Array of locations in the same order as variable names.
  704. */
  705. Effect.prototype.getSpecificUniformLocations = function (names) {
  706. var engine = this._engine;
  707. return engine.getUniforms(this._program, names);
  708. };
  709. /**
  710. * Prepares the effect
  711. */
  712. Effect.prototype._prepareEffect = function () {
  713. var attributesNames = this._attributesNames;
  714. var defines = this.defines;
  715. var fallbacks = this._fallbacks;
  716. this._valueCache = {};
  717. var previousProgram = this._program;
  718. try {
  719. var engine = this._engine;
  720. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  721. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  722. }
  723. else {
  724. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  725. }
  726. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  727. if (engine.supportsUniformBuffers) {
  728. for (var name in this._uniformBuffersNames) {
  729. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  730. }
  731. }
  732. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  733. this._attributes = engine.getAttributes(this._program, attributesNames);
  734. var index;
  735. for (index = 0; index < this._samplers.length; index++) {
  736. var sampler = this.getUniform(this._samplers[index]);
  737. if (sampler == null) {
  738. this._samplers.splice(index, 1);
  739. index--;
  740. }
  741. }
  742. engine.bindSamplers(this);
  743. this._compilationError = "";
  744. this._isReady = true;
  745. if (this.onCompiled) {
  746. this.onCompiled(this);
  747. }
  748. this.onCompileObservable.notifyObservers(this);
  749. this.onCompileObservable.clear();
  750. // Unbind mesh reference in fallbacks
  751. if (this._fallbacks) {
  752. this._fallbacks.unBindMesh();
  753. }
  754. if (previousProgram) {
  755. this.getEngine()._deleteProgram(previousProgram);
  756. }
  757. }
  758. catch (e) {
  759. this._compilationError = e.message;
  760. // Let's go through fallbacks then
  761. BABYLON.Tools.Error("Unable to compile effect:");
  762. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  763. return " " + uniform;
  764. }));
  765. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  766. return " " + attribute;
  767. }));
  768. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  769. BABYLON.Tools.Error("Error: " + this._compilationError);
  770. if (previousProgram) {
  771. this._program = previousProgram;
  772. this._isReady = true;
  773. if (this.onError) {
  774. this.onError(this, this._compilationError);
  775. }
  776. this.onErrorObservable.notifyObservers(this);
  777. }
  778. if (fallbacks && fallbacks.isMoreFallbacks) {
  779. BABYLON.Tools.Error("Trying next fallback.");
  780. this.defines = fallbacks.reduce(this.defines, this);
  781. this._prepareEffect();
  782. }
  783. else {
  784. if (this.onError) {
  785. this.onError(this, this._compilationError);
  786. }
  787. this.onErrorObservable.notifyObservers(this);
  788. this.onErrorObservable.clear();
  789. // Unbind mesh reference in fallbacks
  790. if (this._fallbacks) {
  791. this._fallbacks.unBindMesh();
  792. }
  793. }
  794. }
  795. };
  796. Object.defineProperty(Effect.prototype, "isSupported", {
  797. /**
  798. * Checks if the effect is supported. (Must be called after compilation)
  799. */
  800. get: function () {
  801. return this._compilationError === "";
  802. },
  803. enumerable: true,
  804. configurable: true
  805. });
  806. /**
  807. * Binds a texture to the engine to be used as output of the shader.
  808. * @param channel Name of the output variable.
  809. * @param texture Texture to bind.
  810. */
  811. Effect.prototype._bindTexture = function (channel, texture) {
  812. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  813. };
  814. /**
  815. * Sets a texture on the engine to be used in the shader.
  816. * @param channel Name of the sampler variable.
  817. * @param texture Texture to set.
  818. */
  819. Effect.prototype.setTexture = function (channel, texture) {
  820. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  821. };
  822. /**
  823. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  824. * @param channel Name of the sampler variable.
  825. * @param texture Texture to set.
  826. */
  827. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  828. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  829. };
  830. /**
  831. * Sets an array of textures on the engine to be used in the shader.
  832. * @param channel Name of the variable.
  833. * @param textures Textures to set.
  834. */
  835. Effect.prototype.setTextureArray = function (channel, textures) {
  836. if (this._samplers.indexOf(channel + "Ex") === -1) {
  837. var initialPos = this._samplers.indexOf(channel);
  838. for (var index = 1; index < textures.length; index++) {
  839. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  840. }
  841. }
  842. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  843. };
  844. /**
  845. * 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)
  846. * @param channel Name of the sampler variable.
  847. * @param postProcess Post process to get the input texture from.
  848. */
  849. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  850. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  851. };
  852. /**
  853. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  854. * 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)
  855. * @param channel Name of the sampler variable.
  856. * @param postProcess Post process to get the output texture from.
  857. */
  858. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  859. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  860. };
  861. /** @ignore */
  862. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  863. var cache = this._valueCache[uniformName];
  864. var flag = matrix.updateFlag;
  865. if (cache !== undefined && cache === flag) {
  866. return false;
  867. }
  868. this._valueCache[uniformName] = flag;
  869. return true;
  870. };
  871. /** @ignore */
  872. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  873. var cache = this._valueCache[uniformName];
  874. if (!cache) {
  875. cache = [x, y];
  876. this._valueCache[uniformName] = cache;
  877. return true;
  878. }
  879. var changed = false;
  880. if (cache[0] !== x) {
  881. cache[0] = x;
  882. changed = true;
  883. }
  884. if (cache[1] !== y) {
  885. cache[1] = y;
  886. changed = true;
  887. }
  888. return changed;
  889. };
  890. /** @ignore */
  891. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  892. var cache = this._valueCache[uniformName];
  893. if (!cache) {
  894. cache = [x, y, z];
  895. this._valueCache[uniformName] = cache;
  896. return true;
  897. }
  898. var changed = false;
  899. if (cache[0] !== x) {
  900. cache[0] = x;
  901. changed = true;
  902. }
  903. if (cache[1] !== y) {
  904. cache[1] = y;
  905. changed = true;
  906. }
  907. if (cache[2] !== z) {
  908. cache[2] = z;
  909. changed = true;
  910. }
  911. return changed;
  912. };
  913. /** @ignore */
  914. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  915. var cache = this._valueCache[uniformName];
  916. if (!cache) {
  917. cache = [x, y, z, w];
  918. this._valueCache[uniformName] = cache;
  919. return true;
  920. }
  921. var changed = false;
  922. if (cache[0] !== x) {
  923. cache[0] = x;
  924. changed = true;
  925. }
  926. if (cache[1] !== y) {
  927. cache[1] = y;
  928. changed = true;
  929. }
  930. if (cache[2] !== z) {
  931. cache[2] = z;
  932. changed = true;
  933. }
  934. if (cache[3] !== w) {
  935. cache[3] = w;
  936. changed = true;
  937. }
  938. return changed;
  939. };
  940. /**
  941. * Binds a buffer to a uniform.
  942. * @param buffer Buffer to bind.
  943. * @param name Name of the uniform variable to bind to.
  944. */
  945. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  946. var bufferName = this._uniformBuffersNames[name];
  947. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  948. return;
  949. }
  950. Effect._baseCache[bufferName] = buffer;
  951. this._engine.bindUniformBufferBase(buffer, bufferName);
  952. };
  953. /**
  954. * Binds block to a uniform.
  955. * @param blockName Name of the block to bind.
  956. * @param index Index to bind.
  957. */
  958. Effect.prototype.bindUniformBlock = function (blockName, index) {
  959. this._engine.bindUniformBlock(this._program, blockName, index);
  960. };
  961. /**
  962. * Sets an interger value on a uniform variable.
  963. * @param uniformName Name of the variable.
  964. * @param value Value to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setInt = function (uniformName, value) {
  968. var cache = this._valueCache[uniformName];
  969. if (cache !== undefined && cache === value)
  970. return this;
  971. this._valueCache[uniformName] = value;
  972. this._engine.setInt(this.getUniform(uniformName), value);
  973. return this;
  974. };
  975. /**
  976. * Sets an int array on a uniform variable.
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setIntArray = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setIntArray(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * 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)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setIntArray2 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setIntArray2(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * 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)
  999. * @param uniformName Name of the variable.
  1000. * @param array array to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1004. this._valueCache[uniformName] = null;
  1005. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1006. return this;
  1007. };
  1008. /**
  1009. * 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)
  1010. * @param uniformName Name of the variable.
  1011. * @param array array to be set.
  1012. * @returns this effect.
  1013. */
  1014. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1015. this._valueCache[uniformName] = null;
  1016. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1017. return this;
  1018. };
  1019. /**
  1020. * Sets an float array on a uniform variable.
  1021. * @param uniformName Name of the variable.
  1022. * @param array array to be set.
  1023. * @returns this effect.
  1024. */
  1025. Effect.prototype.setFloatArray = function (uniformName, array) {
  1026. this._valueCache[uniformName] = null;
  1027. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1028. return this;
  1029. };
  1030. /**
  1031. * 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)
  1032. * @param uniformName Name of the variable.
  1033. * @param array array to be set.
  1034. * @returns this effect.
  1035. */
  1036. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1039. return this;
  1040. };
  1041. /**
  1042. * 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)
  1043. * @param uniformName Name of the variable.
  1044. * @param array array to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1048. this._valueCache[uniformName] = null;
  1049. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1050. return this;
  1051. };
  1052. /**
  1053. * 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)
  1054. * @param uniformName Name of the variable.
  1055. * @param array array to be set.
  1056. * @returns this effect.
  1057. */
  1058. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1059. this._valueCache[uniformName] = null;
  1060. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1061. return this;
  1062. };
  1063. /**
  1064. * Sets an array on a uniform variable.
  1065. * @param uniformName Name of the variable.
  1066. * @param array array to be set.
  1067. * @returns this effect.
  1068. */
  1069. Effect.prototype.setArray = function (uniformName, array) {
  1070. this._valueCache[uniformName] = null;
  1071. this._engine.setArray(this.getUniform(uniformName), array);
  1072. return this;
  1073. };
  1074. /**
  1075. * 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)
  1076. * @param uniformName Name of the variable.
  1077. * @param array array to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setArray2 = function (uniformName, array) {
  1081. this._valueCache[uniformName] = null;
  1082. this._engine.setArray2(this.getUniform(uniformName), array);
  1083. return this;
  1084. };
  1085. /**
  1086. * 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)
  1087. * @param uniformName Name of the variable.
  1088. * @param array array to be set.
  1089. * @returns this effect.
  1090. */
  1091. Effect.prototype.setArray3 = function (uniformName, array) {
  1092. this._valueCache[uniformName] = null;
  1093. this._engine.setArray3(this.getUniform(uniformName), array);
  1094. return this;
  1095. };
  1096. /**
  1097. * 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)
  1098. * @param uniformName Name of the variable.
  1099. * @param array array to be set.
  1100. * @returns this effect.
  1101. */
  1102. Effect.prototype.setArray4 = function (uniformName, array) {
  1103. this._valueCache[uniformName] = null;
  1104. this._engine.setArray4(this.getUniform(uniformName), array);
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets matrices on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param matrices matrices to be set.
  1111. * @returns this effect.
  1112. */
  1113. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1114. if (!matrices) {
  1115. return this;
  1116. }
  1117. this._valueCache[uniformName] = null;
  1118. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1119. return this;
  1120. };
  1121. /**
  1122. * Sets matrix on a uniform variable.
  1123. * @param uniformName Name of the variable.
  1124. * @param matrix matrix to be set.
  1125. * @returns this effect.
  1126. */
  1127. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1128. if (this._cacheMatrix(uniformName, matrix)) {
  1129. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1130. }
  1131. return this;
  1132. };
  1133. /**
  1134. * 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)
  1135. * @param uniformName Name of the variable.
  1136. * @param matrix matrix to be set.
  1137. * @returns this effect.
  1138. */
  1139. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1140. this._valueCache[uniformName] = null;
  1141. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1142. return this;
  1143. };
  1144. /**
  1145. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1146. * @param uniformName Name of the variable.
  1147. * @param matrix matrix to be set.
  1148. * @returns this effect.
  1149. */
  1150. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1151. this._valueCache[uniformName] = null;
  1152. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1153. return this;
  1154. };
  1155. /**
  1156. * Sets a float on a uniform variable.
  1157. * @param uniformName Name of the variable.
  1158. * @param value value to be set.
  1159. * @returns this effect.
  1160. */
  1161. Effect.prototype.setFloat = function (uniformName, value) {
  1162. var cache = this._valueCache[uniformName];
  1163. if (cache !== undefined && cache === value)
  1164. return this;
  1165. this._valueCache[uniformName] = value;
  1166. this._engine.setFloat(this.getUniform(uniformName), value);
  1167. return this;
  1168. };
  1169. /**
  1170. * Sets a boolean on a uniform variable.
  1171. * @param uniformName Name of the variable.
  1172. * @param bool value to be set.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setBool = function (uniformName, bool) {
  1176. var cache = this._valueCache[uniformName];
  1177. if (cache !== undefined && cache === bool)
  1178. return this;
  1179. this._valueCache[uniformName] = bool;
  1180. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1181. return this;
  1182. };
  1183. /**
  1184. * Sets a Vector2 on a uniform variable.
  1185. * @param uniformName Name of the variable.
  1186. * @param vector2 vector2 to be set.
  1187. * @returns this effect.
  1188. */
  1189. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1190. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1191. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1192. }
  1193. return this;
  1194. };
  1195. /**
  1196. * Sets a float2 on a uniform variable.
  1197. * @param uniformName Name of the variable.
  1198. * @param x First float in float2.
  1199. * @param y Second float in float2.
  1200. * @returns this effect.
  1201. */
  1202. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1203. if (this._cacheFloat2(uniformName, x, y)) {
  1204. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1205. }
  1206. return this;
  1207. };
  1208. /**
  1209. * Sets a Vector3 on a uniform variable.
  1210. * @param uniformName Name of the variable.
  1211. * @param vector3 Value to be set.
  1212. * @returns this effect.
  1213. */
  1214. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1215. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1216. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1217. }
  1218. return this;
  1219. };
  1220. /**
  1221. * Sets a float3 on a uniform variable.
  1222. * @param uniformName Name of the variable.
  1223. * @param x First float in float3.
  1224. * @param y Second float in float3.
  1225. * @param z Third float in float3.
  1226. * @returns this effect.
  1227. */
  1228. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1229. if (this._cacheFloat3(uniformName, x, y, z)) {
  1230. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1231. }
  1232. return this;
  1233. };
  1234. /**
  1235. * Sets a Vector4 on a uniform variable.
  1236. * @param uniformName Name of the variable.
  1237. * @param vector4 Value to be set.
  1238. * @returns this effect.
  1239. */
  1240. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1241. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1242. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1243. }
  1244. return this;
  1245. };
  1246. /**
  1247. * Sets a float4 on a uniform variable.
  1248. * @param uniformName Name of the variable.
  1249. * @param x First float in float4.
  1250. * @param y Second float in float4.
  1251. * @param z Third float in float4.
  1252. * @param w Fourth float in float4.
  1253. * @returns this effect.
  1254. */
  1255. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1256. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1257. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1258. }
  1259. return this;
  1260. };
  1261. /**
  1262. * Sets a Color3 on a uniform variable.
  1263. * @param uniformName Name of the variable.
  1264. * @param color3 Value to be set.
  1265. * @returns this effect.
  1266. */
  1267. Effect.prototype.setColor3 = function (uniformName, color3) {
  1268. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1269. this._engine.setColor3(this.getUniform(uniformName), color3);
  1270. }
  1271. return this;
  1272. };
  1273. /**
  1274. * Sets a Color4 on a uniform variable.
  1275. * @param uniformName Name of the variable.
  1276. * @param color3 Value to be set.
  1277. * @param alpha Alpha value to be set.
  1278. * @returns this effect.
  1279. */
  1280. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1281. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1282. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1283. }
  1284. return this;
  1285. };
  1286. /**
  1287. * Sets a Color4 on a uniform variable
  1288. * @param uniformName defines the name of the variable
  1289. * @param color4 defines the value to be set
  1290. * @returns this effect.
  1291. */
  1292. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1293. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1294. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1295. }
  1296. return this;
  1297. };
  1298. /**
  1299. * Resets the cache of effects.
  1300. */
  1301. Effect.ResetCache = function () {
  1302. Effect._baseCache = {};
  1303. };
  1304. Effect._uniqueIdSeed = 0;
  1305. Effect._baseCache = {};
  1306. /**
  1307. * Store of each shader (The can be looked up using effect.key)
  1308. */
  1309. Effect.ShadersStore = {};
  1310. /**
  1311. * Store of each included file for a shader (The can be looked up using effect.key)
  1312. */
  1313. Effect.IncludesShadersStore = {};
  1314. return Effect;
  1315. }());
  1316. BABYLON.Effect = Effect;
  1317. })(BABYLON || (BABYLON = {}));
  1318. //# sourceMappingURL=babylon.effect.js.map
  1319. "use strict";
  1320. //# sourceMappingURL=babylon.types.js.map
  1321. "use strict";
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. "use strict";
  1371. var BABYLON;
  1372. (function (BABYLON) {
  1373. var PointerEventTypes = /** @class */ (function () {
  1374. function PointerEventTypes() {
  1375. }
  1376. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1377. get: function () {
  1378. return PointerEventTypes._POINTERDOWN;
  1379. },
  1380. enumerable: true,
  1381. configurable: true
  1382. });
  1383. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1384. get: function () {
  1385. return PointerEventTypes._POINTERUP;
  1386. },
  1387. enumerable: true,
  1388. configurable: true
  1389. });
  1390. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1391. get: function () {
  1392. return PointerEventTypes._POINTERMOVE;
  1393. },
  1394. enumerable: true,
  1395. configurable: true
  1396. });
  1397. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1398. get: function () {
  1399. return PointerEventTypes._POINTERWHEEL;
  1400. },
  1401. enumerable: true,
  1402. configurable: true
  1403. });
  1404. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1405. get: function () {
  1406. return PointerEventTypes._POINTERPICK;
  1407. },
  1408. enumerable: true,
  1409. configurable: true
  1410. });
  1411. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1412. get: function () {
  1413. return PointerEventTypes._POINTERTAP;
  1414. },
  1415. enumerable: true,
  1416. configurable: true
  1417. });
  1418. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1419. get: function () {
  1420. return PointerEventTypes._POINTERDOUBLETAP;
  1421. },
  1422. enumerable: true,
  1423. configurable: true
  1424. });
  1425. PointerEventTypes._POINTERDOWN = 0x01;
  1426. PointerEventTypes._POINTERUP = 0x02;
  1427. PointerEventTypes._POINTERMOVE = 0x04;
  1428. PointerEventTypes._POINTERWHEEL = 0x08;
  1429. PointerEventTypes._POINTERPICK = 0x10;
  1430. PointerEventTypes._POINTERTAP = 0x20;
  1431. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1432. return PointerEventTypes;
  1433. }());
  1434. BABYLON.PointerEventTypes = PointerEventTypes;
  1435. var PointerInfoBase = /** @class */ (function () {
  1436. function PointerInfoBase(type, event) {
  1437. this.type = type;
  1438. this.event = event;
  1439. }
  1440. return PointerInfoBase;
  1441. }());
  1442. BABYLON.PointerInfoBase = PointerInfoBase;
  1443. /**
  1444. * This class is used to store pointer related info for the onPrePointerObservable event.
  1445. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1446. */
  1447. var PointerInfoPre = /** @class */ (function (_super) {
  1448. __extends(PointerInfoPre, _super);
  1449. function PointerInfoPre(type, event, localX, localY) {
  1450. var _this = _super.call(this, type, event) || this;
  1451. _this.skipOnPointerObservable = false;
  1452. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1453. return _this;
  1454. }
  1455. return PointerInfoPre;
  1456. }(PointerInfoBase));
  1457. BABYLON.PointerInfoPre = PointerInfoPre;
  1458. /**
  1459. * This type contains all the data related to a pointer event in Babylon.js.
  1460. * 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.
  1461. */
  1462. var PointerInfo = /** @class */ (function (_super) {
  1463. __extends(PointerInfo, _super);
  1464. function PointerInfo(type, event, pickInfo) {
  1465. var _this = _super.call(this, type, event) || this;
  1466. _this.pickInfo = pickInfo;
  1467. return _this;
  1468. }
  1469. return PointerInfo;
  1470. }(PointerInfoBase));
  1471. BABYLON.PointerInfo = PointerInfo;
  1472. })(BABYLON || (BABYLON = {}));
  1473. //# sourceMappingURL=babylon.pointerEvents.js.map
  1474. "use strict";
  1475. var BABYLON;
  1476. (function (BABYLON) {
  1477. BABYLON.ToGammaSpace = 1 / 2.2;
  1478. BABYLON.ToLinearSpace = 2.2;
  1479. BABYLON.Epsilon = 0.001;
  1480. /**
  1481. * Class used to hold a RBG color
  1482. */
  1483. var Color3 = /** @class */ (function () {
  1484. /**
  1485. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1486. * @param r defines the red component (between 0 and 1, default is 0)
  1487. * @param g defines the green component (between 0 and 1, default is 0)
  1488. * @param b defines the blue component (between 0 and 1, default is 0)
  1489. */
  1490. function Color3(
  1491. /**
  1492. * Defines the red component (between 0 and 1, default is 0)
  1493. */
  1494. r,
  1495. /**
  1496. * Defines the green component (between 0 and 1, default is 0)
  1497. */
  1498. g,
  1499. /**
  1500. * Defines the blue component (between 0 and 1, default is 0)
  1501. */
  1502. b) {
  1503. if (r === void 0) { r = 0; }
  1504. if (g === void 0) { g = 0; }
  1505. if (b === void 0) { b = 0; }
  1506. this.r = r;
  1507. this.g = g;
  1508. this.b = b;
  1509. }
  1510. /**
  1511. * Creates a string with the Color3 current values
  1512. * @returns the string representation of the Color3 object
  1513. */
  1514. Color3.prototype.toString = function () {
  1515. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1516. };
  1517. /**
  1518. * Returns the string "Color3"
  1519. * @returns "Color3"
  1520. */
  1521. Color3.prototype.getClassName = function () {
  1522. return "Color3";
  1523. };
  1524. /**
  1525. * Compute the Color3 hash code
  1526. * @returns an unique number that can be used to hash Color3 objects
  1527. */
  1528. Color3.prototype.getHashCode = function () {
  1529. var hash = this.r || 0;
  1530. hash = (hash * 397) ^ (this.g || 0);
  1531. hash = (hash * 397) ^ (this.b || 0);
  1532. return hash;
  1533. };
  1534. // Operators
  1535. /**
  1536. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1537. * @param array defines the array where to store the r,g,b components
  1538. * @param index defines an optional index in the target array to define where to start storing values
  1539. * @returns the current Color3 object
  1540. */
  1541. Color3.prototype.toArray = function (array, index) {
  1542. if (index === undefined) {
  1543. index = 0;
  1544. }
  1545. array[index] = this.r;
  1546. array[index + 1] = this.g;
  1547. array[index + 2] = this.b;
  1548. return this;
  1549. };
  1550. /**
  1551. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1552. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1553. * @returns a new {BABYLON.Color4} object
  1554. */
  1555. Color3.prototype.toColor4 = function (alpha) {
  1556. if (alpha === void 0) { alpha = 1; }
  1557. return new Color4(this.r, this.g, this.b, alpha);
  1558. };
  1559. /**
  1560. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1561. * @returns the new array
  1562. */
  1563. Color3.prototype.asArray = function () {
  1564. var result = new Array();
  1565. this.toArray(result, 0);
  1566. return result;
  1567. };
  1568. /**
  1569. * Returns the luminance value
  1570. * @returns a float value
  1571. */
  1572. Color3.prototype.toLuminance = function () {
  1573. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1574. };
  1575. /**
  1576. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1577. * @param otherColor defines the second operand
  1578. * @returns the new Color3 object
  1579. */
  1580. Color3.prototype.multiply = function (otherColor) {
  1581. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1582. };
  1583. /**
  1584. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1585. * @param otherColor defines the second operand
  1586. * @param result defines the Color3 object where to store the result
  1587. * @returns the current Color3
  1588. */
  1589. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1590. result.r = this.r * otherColor.r;
  1591. result.g = this.g * otherColor.g;
  1592. result.b = this.b * otherColor.b;
  1593. return this;
  1594. };
  1595. /**
  1596. * Determines equality between Color3 objects
  1597. * @param otherColor defines the second operand
  1598. * @returns true if the rgb values are equal to the given ones
  1599. */
  1600. Color3.prototype.equals = function (otherColor) {
  1601. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1602. };
  1603. /**
  1604. * Determines equality between the current Color3 object and a set of r,b,g values
  1605. * @param r defines the red component to check
  1606. * @param g defines the green component to check
  1607. * @param b defines the blue component to check
  1608. * @returns true if the rgb values are equal to the given ones
  1609. */
  1610. Color3.prototype.equalsFloats = function (r, g, b) {
  1611. return this.r === r && this.g === g && this.b === b;
  1612. };
  1613. /**
  1614. * Multiplies in place each rgb value by scale
  1615. * @param scale defines the scaling factor
  1616. * @returns the updated Color3
  1617. */
  1618. Color3.prototype.scale = function (scale) {
  1619. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1620. };
  1621. /**
  1622. * Multiplies the rgb values by scale and stores the result into "result"
  1623. * @param scale defines the scaling factor
  1624. * @param result defines the Color3 object where to store the result
  1625. * @returns the unmodified current Color3
  1626. */
  1627. Color3.prototype.scaleToRef = function (scale, result) {
  1628. result.r = this.r * scale;
  1629. result.g = this.g * scale;
  1630. result.b = this.b * scale;
  1631. return this;
  1632. };
  1633. /**
  1634. * Scale the current Color3 values by a factor and add the result to a given Color3
  1635. * @param scale defines the scale factor
  1636. * @param result defines color to store the result into
  1637. * @returns the unmodified current Color3
  1638. */
  1639. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1640. result.r += this.r * scale;
  1641. result.g += this.g * scale;
  1642. result.b += this.b * scale;
  1643. return this;
  1644. };
  1645. /**
  1646. * Clamps the rgb values by the min and max values and stores the result into "result"
  1647. * @param min defines minimum clamping value (default is 0)
  1648. * @param max defines maximum clamping value (default is 1)
  1649. * @param result defines color to store the result into
  1650. * @returns the original Color3
  1651. */
  1652. Color3.prototype.clampToRef = function (min, max, result) {
  1653. if (min === void 0) { min = 0; }
  1654. if (max === void 0) { max = 1; }
  1655. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1656. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1657. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1658. return this;
  1659. };
  1660. /**
  1661. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1662. * @param otherColor defines the second operand
  1663. * @returns the new Color3
  1664. */
  1665. Color3.prototype.add = function (otherColor) {
  1666. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1667. };
  1668. /**
  1669. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1670. * @param otherColor defines the second operand
  1671. * @param result defines Color3 object to store the result into
  1672. * @returns the unmodified current Color3
  1673. */
  1674. Color3.prototype.addToRef = function (otherColor, result) {
  1675. result.r = this.r + otherColor.r;
  1676. result.g = this.g + otherColor.g;
  1677. result.b = this.b + otherColor.b;
  1678. return this;
  1679. };
  1680. /**
  1681. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1682. * @param otherColor defines the second operand
  1683. * @returns the new Color3
  1684. */
  1685. Color3.prototype.subtract = function (otherColor) {
  1686. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1687. };
  1688. /**
  1689. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1690. * @param otherColor defines the second operand
  1691. * @param result defines Color3 object to store the result into
  1692. * @returns the unmodified current Color3
  1693. */
  1694. Color3.prototype.subtractToRef = function (otherColor, result) {
  1695. result.r = this.r - otherColor.r;
  1696. result.g = this.g - otherColor.g;
  1697. result.b = this.b - otherColor.b;
  1698. return this;
  1699. };
  1700. /**
  1701. * Copy the current object
  1702. * @returns a new Color3 copied the current one
  1703. */
  1704. Color3.prototype.clone = function () {
  1705. return new Color3(this.r, this.g, this.b);
  1706. };
  1707. /**
  1708. * Copies the rgb values from the source in the current Color3
  1709. * @param source defines the source Color3 object
  1710. * @returns the updated Color3 object
  1711. */
  1712. Color3.prototype.copyFrom = function (source) {
  1713. this.r = source.r;
  1714. this.g = source.g;
  1715. this.b = source.b;
  1716. return this;
  1717. };
  1718. /**
  1719. * Updates the Color3 rgb values from the given floats
  1720. * @param r defines the red component to read from
  1721. * @param g defines the green component to read from
  1722. * @param b defines the blue component to read from
  1723. * @returns the current Color3 object
  1724. */
  1725. Color3.prototype.copyFromFloats = function (r, g, b) {
  1726. this.r = r;
  1727. this.g = g;
  1728. this.b = b;
  1729. return this;
  1730. };
  1731. /**
  1732. * Updates the Color3 rgb values from the given floats
  1733. * @param r defines the red component to read from
  1734. * @param g defines the green component to read from
  1735. * @param b defines the blue component to read from
  1736. * @returns the current Color3 object
  1737. */
  1738. Color3.prototype.set = function (r, g, b) {
  1739. return this.copyFromFloats(r, g, b);
  1740. };
  1741. /**
  1742. * Compute the Color3 hexadecimal code as a string
  1743. * @returns a string containing the hexadecimal representation of the Color3 object
  1744. */
  1745. Color3.prototype.toHexString = function () {
  1746. var intR = (this.r * 255) | 0;
  1747. var intG = (this.g * 255) | 0;
  1748. var intB = (this.b * 255) | 0;
  1749. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1750. };
  1751. /**
  1752. * Computes a new Color3 converted from the current one to linear space
  1753. * @returns a new Color3 object
  1754. */
  1755. Color3.prototype.toLinearSpace = function () {
  1756. var convertedColor = new Color3();
  1757. this.toLinearSpaceToRef(convertedColor);
  1758. return convertedColor;
  1759. };
  1760. /**
  1761. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1762. * @param convertedColor defines the Color3 object where to store the linear space version
  1763. * @returns the unmodified Color3
  1764. */
  1765. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1766. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1767. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1768. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1769. return this;
  1770. };
  1771. /**
  1772. * Computes a new Color3 converted from the current one to gamma space
  1773. * @returns a new Color3 object
  1774. */
  1775. Color3.prototype.toGammaSpace = function () {
  1776. var convertedColor = new Color3();
  1777. this.toGammaSpaceToRef(convertedColor);
  1778. return convertedColor;
  1779. };
  1780. /**
  1781. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1782. * @param convertedColor defines the Color3 object where to store the gamma space version
  1783. * @returns the unmodified Color3
  1784. */
  1785. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1786. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1787. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1788. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1789. return this;
  1790. };
  1791. // Statics
  1792. /**
  1793. * Creates a new Color3 from the string containing valid hexadecimal values
  1794. * @param hex defines a string containing valid hexadecimal values
  1795. * @returns a new Color3 object
  1796. */
  1797. Color3.FromHexString = function (hex) {
  1798. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1799. return new Color3(0, 0, 0);
  1800. }
  1801. var r = parseInt(hex.substring(1, 3), 16);
  1802. var g = parseInt(hex.substring(3, 5), 16);
  1803. var b = parseInt(hex.substring(5, 7), 16);
  1804. return Color3.FromInts(r, g, b);
  1805. };
  1806. /**
  1807. * Creates a new Vector3 from the starting index of the given array
  1808. * @param array defines the source array
  1809. * @param offset defines an offset in the source array
  1810. * @returns a new Color3 object
  1811. */
  1812. Color3.FromArray = function (array, offset) {
  1813. if (offset === void 0) { offset = 0; }
  1814. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1815. };
  1816. /**
  1817. * Creates a new Color3 from integer values (< 256)
  1818. * @param r defines the red component to read from (value between 0 and 255)
  1819. * @param g defines the green component to read from (value between 0 and 255)
  1820. * @param b defines the blue component to read from (value between 0 and 255)
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.FromInts = function (r, g, b) {
  1824. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1825. };
  1826. /**
  1827. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1828. * @param start defines the start Color3 value
  1829. * @param end defines the end Color3 value
  1830. * @param amount defines the gradient value between start and end
  1831. * @returns a new Color3 object
  1832. */
  1833. Color3.Lerp = function (start, end, amount) {
  1834. var r = start.r + ((end.r - start.r) * amount);
  1835. var g = start.g + ((end.g - start.g) * amount);
  1836. var b = start.b + ((end.b - start.b) * amount);
  1837. return new Color3(r, g, b);
  1838. };
  1839. /**
  1840. * Returns a Color3 value containing a red color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.Red = function () { return new Color3(1, 0, 0); };
  1844. /**
  1845. * Returns a Color3 value containing a green color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Green = function () { return new Color3(0, 1, 0); };
  1849. /**
  1850. * Returns a Color3 value containing a blue color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1854. /**
  1855. * Returns a Color3 value containing a black color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.Black = function () { return new Color3(0, 0, 0); };
  1859. /**
  1860. * Returns a Color3 value containing a white color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.White = function () { return new Color3(1, 1, 1); };
  1864. /**
  1865. * Returns a Color3 value containing a purple color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1869. /**
  1870. * Returns a Color3 value containing a magenta color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1874. /**
  1875. * Returns a Color3 value containing a yellow color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1879. /**
  1880. * Returns a Color3 value containing a gray color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1884. /**
  1885. * Returns a Color3 value containing a teal color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1889. /**
  1890. * Returns a Color3 value containing a random color
  1891. * @returns a new Color3 object
  1892. */
  1893. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1894. return Color3;
  1895. }());
  1896. BABYLON.Color3 = Color3;
  1897. /**
  1898. * Class used to hold a RBGA color
  1899. */
  1900. var Color4 = /** @class */ (function () {
  1901. /**
  1902. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1903. * @param r defines the red component (between 0 and 1, default is 0)
  1904. * @param g defines the green component (between 0 and 1, default is 0)
  1905. * @param b defines the blue component (between 0 and 1, default is 0)
  1906. * @param a defines the alpha component (between 0 and 1, default is 1)
  1907. */
  1908. function Color4(
  1909. /**
  1910. * Defines the red component (between 0 and 1, default is 0)
  1911. */
  1912. r,
  1913. /**
  1914. * Defines the green component (between 0 and 1, default is 0)
  1915. */
  1916. g,
  1917. /**
  1918. * Defines the blue component (between 0 and 1, default is 0)
  1919. */
  1920. b,
  1921. /**
  1922. * Defines the alpha component (between 0 and 1, default is 1)
  1923. */
  1924. a) {
  1925. if (r === void 0) { r = 0; }
  1926. if (g === void 0) { g = 0; }
  1927. if (b === void 0) { b = 0; }
  1928. if (a === void 0) { a = 1; }
  1929. this.r = r;
  1930. this.g = g;
  1931. this.b = b;
  1932. this.a = a;
  1933. }
  1934. // Operators
  1935. /**
  1936. * Adds in place the given Color4 values to the current Color4 object
  1937. * @param right defines the second operand
  1938. * @returns the current updated Color4 object
  1939. */
  1940. Color4.prototype.addInPlace = function (right) {
  1941. this.r += right.r;
  1942. this.g += right.g;
  1943. this.b += right.b;
  1944. this.a += right.a;
  1945. return this;
  1946. };
  1947. /**
  1948. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1949. * @returns the new array
  1950. */
  1951. Color4.prototype.asArray = function () {
  1952. var result = new Array();
  1953. this.toArray(result, 0);
  1954. return result;
  1955. };
  1956. /**
  1957. * Stores from the starting index in the given array the Color4 successive values
  1958. * @param array defines the array where to store the r,g,b components
  1959. * @param index defines an optional index in the target array to define where to start storing values
  1960. * @returns the current Color4 object
  1961. */
  1962. Color4.prototype.toArray = function (array, index) {
  1963. if (index === undefined) {
  1964. index = 0;
  1965. }
  1966. array[index] = this.r;
  1967. array[index + 1] = this.g;
  1968. array[index + 2] = this.b;
  1969. array[index + 3] = this.a;
  1970. return this;
  1971. };
  1972. /**
  1973. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1974. * @param right defines the second operand
  1975. * @returns a new Color4 object
  1976. */
  1977. Color4.prototype.add = function (right) {
  1978. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1979. };
  1980. /**
  1981. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1982. * @param right defines the second operand
  1983. * @returns a new Color4 object
  1984. */
  1985. Color4.prototype.subtract = function (right) {
  1986. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1987. };
  1988. /**
  1989. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1990. * @param right defines the second operand
  1991. * @param result defines the Color4 object where to store the result
  1992. * @returns the current Color4 object
  1993. */
  1994. Color4.prototype.subtractToRef = function (right, result) {
  1995. result.r = this.r - right.r;
  1996. result.g = this.g - right.g;
  1997. result.b = this.b - right.b;
  1998. result.a = this.a - right.a;
  1999. return this;
  2000. };
  2001. /**
  2002. * Creates a new Color4 with the current Color4 values multiplied by scale
  2003. * @param scale defines the scaling factor to apply
  2004. * @returns a new Color4 object
  2005. */
  2006. Color4.prototype.scale = function (scale) {
  2007. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2008. };
  2009. /**
  2010. * Multiplies the current Color4 values by scale and stores the result in "result"
  2011. * @param scale defines the scaling factor to apply
  2012. * @param result defines the Color4 object where to store the result
  2013. * @returns the current unmodified Color4
  2014. */
  2015. Color4.prototype.scaleToRef = function (scale, result) {
  2016. result.r = this.r * scale;
  2017. result.g = this.g * scale;
  2018. result.b = this.b * scale;
  2019. result.a = this.a * scale;
  2020. return this;
  2021. };
  2022. /**
  2023. * Scale the current Color4 values by a factor and add the result to a given Color4
  2024. * @param scale defines the scale factor
  2025. * @param result defines the Color4 object where to store the result
  2026. * @returns the unmodified current Color4
  2027. */
  2028. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2029. result.r += this.r * scale;
  2030. result.g += this.g * scale;
  2031. result.b += this.b * scale;
  2032. result.a += this.a * scale;
  2033. return this;
  2034. };
  2035. /**
  2036. * Clamps the rgb values by the min and max values and stores the result into "result"
  2037. * @param min defines minimum clamping value (default is 0)
  2038. * @param max defines maximum clamping value (default is 1)
  2039. * @param result defines color to store the result into.
  2040. * @returns the cuurent Color4
  2041. */
  2042. Color4.prototype.clampToRef = function (min, max, result) {
  2043. if (min === void 0) { min = 0; }
  2044. if (max === void 0) { max = 1; }
  2045. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2046. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2047. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2048. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2049. return this;
  2050. };
  2051. /**
  2052. * Multipy an Color4 value by another and return a new Color4 object
  2053. * @param color defines the Color4 value to multiply by
  2054. * @returns a new Color4 object
  2055. */
  2056. Color4.prototype.multiply = function (color) {
  2057. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2058. };
  2059. /**
  2060. * Multipy a Color4 value by another and push the result in a reference value
  2061. * @param color defines the Color4 value to multiply by
  2062. * @param result defines the Color4 to fill the result in
  2063. * @returns the result Color4
  2064. */
  2065. Color4.prototype.multiplyToRef = function (color, result) {
  2066. result.r = this.r * color.r;
  2067. result.g = this.g * color.g;
  2068. result.b = this.b * color.b;
  2069. result.a = this.a * color.a;
  2070. return result;
  2071. };
  2072. /**
  2073. * Creates a string with the Color4 current values
  2074. * @returns the string representation of the Color4 object
  2075. */
  2076. Color4.prototype.toString = function () {
  2077. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2078. };
  2079. /**
  2080. * Returns the string "Color4"
  2081. * @returns "Color4"
  2082. */
  2083. Color4.prototype.getClassName = function () {
  2084. return "Color4";
  2085. };
  2086. /**
  2087. * Compute the Color4 hash code
  2088. * @returns an unique number that can be used to hash Color4 objects
  2089. */
  2090. Color4.prototype.getHashCode = function () {
  2091. var hash = this.r || 0;
  2092. hash = (hash * 397) ^ (this.g || 0);
  2093. hash = (hash * 397) ^ (this.b || 0);
  2094. hash = (hash * 397) ^ (this.a || 0);
  2095. return hash;
  2096. };
  2097. /**
  2098. * Creates a new Color4 copied from the current one
  2099. * @returns a new Color4 object
  2100. */
  2101. Color4.prototype.clone = function () {
  2102. return new Color4(this.r, this.g, this.b, this.a);
  2103. };
  2104. /**
  2105. * Copies the given Color4 values into the current one
  2106. * @param source defines the source Color4 object
  2107. * @returns the current updated Color4 object
  2108. */
  2109. Color4.prototype.copyFrom = function (source) {
  2110. this.r = source.r;
  2111. this.g = source.g;
  2112. this.b = source.b;
  2113. this.a = source.a;
  2114. return this;
  2115. };
  2116. /**
  2117. * Copies the given float values into the current one
  2118. * @param r defines the red component to read from
  2119. * @param g defines the green component to read from
  2120. * @param b defines the blue component to read from
  2121. * @param a defines the alpha component to read from
  2122. * @returns the current updated Color4 object
  2123. */
  2124. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2125. this.r = r;
  2126. this.g = g;
  2127. this.b = b;
  2128. this.a = a;
  2129. return this;
  2130. };
  2131. /**
  2132. * Copies the given float values into the current one
  2133. * @param r defines the red component to read from
  2134. * @param g defines the green component to read from
  2135. * @param b defines the blue component to read from
  2136. * @param a defines the alpha component to read from
  2137. * @returns the current updated Color4 object
  2138. */
  2139. Color4.prototype.set = function (r, g, b, a) {
  2140. return this.copyFromFloats(r, g, b, a);
  2141. };
  2142. /**
  2143. * Compute the Color4 hexadecimal code as a string
  2144. * @returns a string containing the hexadecimal representation of the Color4 object
  2145. */
  2146. Color4.prototype.toHexString = function () {
  2147. var intR = (this.r * 255) | 0;
  2148. var intG = (this.g * 255) | 0;
  2149. var intB = (this.b * 255) | 0;
  2150. var intA = (this.a * 255) | 0;
  2151. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2152. };
  2153. /**
  2154. * Computes a new Color4 converted from the current one to linear space
  2155. * @returns a new Color4 object
  2156. */
  2157. Color4.prototype.toLinearSpace = function () {
  2158. var convertedColor = new Color4();
  2159. this.toLinearSpaceToRef(convertedColor);
  2160. return convertedColor;
  2161. };
  2162. /**
  2163. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2164. * @param convertedColor defines the Color4 object where to store the linear space version
  2165. * @returns the unmodified Color4
  2166. */
  2167. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2168. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2169. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2170. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2171. convertedColor.a = this.a;
  2172. return this;
  2173. };
  2174. /**
  2175. * Computes a new Color4 converted from the current one to gamma space
  2176. * @returns a new Color4 object
  2177. */
  2178. Color4.prototype.toGammaSpace = function () {
  2179. var convertedColor = new Color4();
  2180. this.toGammaSpaceToRef(convertedColor);
  2181. return convertedColor;
  2182. };
  2183. /**
  2184. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2185. * @param convertedColor defines the Color4 object where to store the gamma space version
  2186. * @returns the unmodified Color4
  2187. */
  2188. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2189. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2190. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2191. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2192. convertedColor.a = this.a;
  2193. return this;
  2194. };
  2195. // Statics
  2196. /**
  2197. * Creates a new Color4 from the string containing valid hexadecimal values
  2198. * @param hex defines a string containing valid hexadecimal values
  2199. * @returns a new Color4 object
  2200. */
  2201. Color4.FromHexString = function (hex) {
  2202. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2203. return new Color4(0.0, 0.0, 0.0, 0.0);
  2204. }
  2205. var r = parseInt(hex.substring(1, 3), 16);
  2206. var g = parseInt(hex.substring(3, 5), 16);
  2207. var b = parseInt(hex.substring(5, 7), 16);
  2208. var a = parseInt(hex.substring(7, 9), 16);
  2209. return Color4.FromInts(r, g, b, a);
  2210. };
  2211. /**
  2212. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2213. * @param left defines the start value
  2214. * @param right defines the end value
  2215. * @param amount defines the gradient factor
  2216. * @returns a new Color4 object
  2217. */
  2218. Color4.Lerp = function (left, right, amount) {
  2219. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2220. Color4.LerpToRef(left, right, amount, result);
  2221. return result;
  2222. };
  2223. /**
  2224. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2225. * @param left defines the start value
  2226. * @param right defines the end value
  2227. * @param amount defines the gradient factor
  2228. * @param result defines the Color4 object where to store data
  2229. */
  2230. Color4.LerpToRef = function (left, right, amount, result) {
  2231. result.r = left.r + (right.r - left.r) * amount;
  2232. result.g = left.g + (right.g - left.g) * amount;
  2233. result.b = left.b + (right.b - left.b) * amount;
  2234. result.a = left.a + (right.a - left.a) * amount;
  2235. };
  2236. /**
  2237. * Creates a new Color4 from the starting index element of the given array
  2238. * @param array defines the source array to read from
  2239. * @param offset defines the offset in the source array
  2240. * @returns a new Color4 object
  2241. */
  2242. Color4.FromArray = function (array, offset) {
  2243. if (offset === void 0) { offset = 0; }
  2244. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2245. };
  2246. /**
  2247. * Creates a new Color3 from integer values (< 256)
  2248. * @param r defines the red component to read from (value between 0 and 255)
  2249. * @param g defines the green component to read from (value between 0 and 255)
  2250. * @param b defines the blue component to read from (value between 0 and 255)
  2251. * @param a defines the alpha component to read from (value between 0 and 255)
  2252. * @returns a new Color3 object
  2253. */
  2254. Color4.FromInts = function (r, g, b, a) {
  2255. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2256. };
  2257. /**
  2258. * Check the content of a given array and convert it to an array containing RGBA data
  2259. * If the original array was already containing count * 4 values then it is returned directly
  2260. * @param colors defines the array to check
  2261. * @param count defines the number of RGBA data to expect
  2262. * @returns an array containing count * 4 values (RGBA)
  2263. */
  2264. Color4.CheckColors4 = function (colors, count) {
  2265. // Check if color3 was used
  2266. if (colors.length === count * 3) {
  2267. var colors4 = [];
  2268. for (var index = 0; index < colors.length; index += 3) {
  2269. var newIndex = (index / 3) * 4;
  2270. colors4[newIndex] = colors[index];
  2271. colors4[newIndex + 1] = colors[index + 1];
  2272. colors4[newIndex + 2] = colors[index + 2];
  2273. colors4[newIndex + 3] = 1.0;
  2274. }
  2275. return colors4;
  2276. }
  2277. return colors;
  2278. };
  2279. return Color4;
  2280. }());
  2281. BABYLON.Color4 = Color4;
  2282. var Vector2 = /** @class */ (function () {
  2283. /**
  2284. * Creates a new Vector2 from the given x and y coordinates.
  2285. */
  2286. function Vector2(x, y) {
  2287. this.x = x;
  2288. this.y = y;
  2289. }
  2290. /**
  2291. * Returns a string with the Vector2 coordinates.
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Returns the string "Vector2"
  2298. */
  2299. Vector2.prototype.getClassName = function () {
  2300. return "Vector2";
  2301. };
  2302. /**
  2303. * Returns the Vector2 hash code as a number.
  2304. */
  2305. Vector2.prototype.getHashCode = function () {
  2306. var hash = this.x || 0;
  2307. hash = (hash * 397) ^ (this.y || 0);
  2308. return hash;
  2309. };
  2310. // Operators
  2311. /**
  2312. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2313. * Returns the Vector2.
  2314. */
  2315. Vector2.prototype.toArray = function (array, index) {
  2316. if (index === void 0) { index = 0; }
  2317. array[index] = this.x;
  2318. array[index + 1] = this.y;
  2319. return this;
  2320. };
  2321. /**
  2322. * Returns a new array with 2 elements : the Vector2 coordinates.
  2323. */
  2324. Vector2.prototype.asArray = function () {
  2325. var result = new Array();
  2326. this.toArray(result, 0);
  2327. return result;
  2328. };
  2329. /**
  2330. * Sets the Vector2 coordinates with the given Vector2 coordinates.
  2331. * Returns the updated Vector2.
  2332. */
  2333. Vector2.prototype.copyFrom = function (source) {
  2334. this.x = source.x;
  2335. this.y = source.y;
  2336. return this;
  2337. };
  2338. /**
  2339. * Sets the Vector2 coordinates with the given floats.
  2340. * Returns the updated Vector2.
  2341. */
  2342. Vector2.prototype.copyFromFloats = function (x, y) {
  2343. this.x = x;
  2344. this.y = y;
  2345. return this;
  2346. };
  2347. /**
  2348. * Sets the Vector2 coordinates with the given floats.
  2349. * Returns the updated Vector2.
  2350. */
  2351. Vector2.prototype.set = function (x, y) {
  2352. return this.copyFromFloats(x, y);
  2353. };
  2354. /**
  2355. * Returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates.
  2356. */
  2357. Vector2.prototype.add = function (otherVector) {
  2358. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2359. };
  2360. /**
  2361. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates.
  2362. * Returns the Vector2.
  2363. */
  2364. Vector2.prototype.addToRef = function (otherVector, result) {
  2365. result.x = this.x + otherVector.x;
  2366. result.y = this.y + otherVector.y;
  2367. return this;
  2368. };
  2369. /**
  2370. * Set the Vector2 coordinates by adding the given Vector2 coordinates.
  2371. * Returns the updated Vector2.
  2372. */
  2373. Vector2.prototype.addInPlace = function (otherVector) {
  2374. this.x += otherVector.x;
  2375. this.y += otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Returns a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates.
  2380. */
  2381. Vector2.prototype.addVector3 = function (otherVector) {
  2382. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2383. };
  2384. /**
  2385. * Returns a new Vector2 set with the subtracted coordinates of the given one from the current Vector2.
  2386. */
  2387. Vector2.prototype.subtract = function (otherVector) {
  2388. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2389. };
  2390. /**
  2391. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2392. * Returns the Vector2.
  2393. */
  2394. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2395. result.x = this.x - otherVector.x;
  2396. result.y = this.y - otherVector.y;
  2397. return this;
  2398. };
  2399. /**
  2400. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates.
  2401. * Returns the updated Vector2.
  2402. */
  2403. Vector2.prototype.subtractInPlace = function (otherVector) {
  2404. this.x -= otherVector.x;
  2405. this.y -= otherVector.y;
  2406. return this;
  2407. };
  2408. /**
  2409. * Multiplies in place the current Vector2 coordinates by the given ones.
  2410. * Returns the updated Vector2.
  2411. */
  2412. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2413. this.x *= otherVector.x;
  2414. this.y *= otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates.
  2419. */
  2420. Vector2.prototype.multiply = function (otherVector) {
  2421. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2422. };
  2423. /**
  2424. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates.
  2425. * Returns the Vector2.
  2426. */
  2427. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2428. result.x = this.x * otherVector.x;
  2429. result.y = this.y * otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the given floats.
  2434. */
  2435. Vector2.prototype.multiplyByFloats = function (x, y) {
  2436. return new Vector2(this.x * x, this.y * y);
  2437. };
  2438. /**
  2439. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates.
  2440. */
  2441. Vector2.prototype.divide = function (otherVector) {
  2442. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2443. };
  2444. /**
  2445. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates.
  2446. * Returns the Vector2.
  2447. */
  2448. Vector2.prototype.divideToRef = function (otherVector, result) {
  2449. result.x = this.x / otherVector.x;
  2450. result.y = this.y / otherVector.y;
  2451. return this;
  2452. };
  2453. /**
  2454. * Divides the current Vector3 coordinates by the given ones.
  2455. * Returns the updated Vector3.
  2456. */
  2457. Vector2.prototype.divideInPlace = function (otherVector) {
  2458. return this.divideToRef(otherVector, this);
  2459. };
  2460. /**
  2461. * Returns a new Vector2 with current Vector2 negated coordinates.
  2462. */
  2463. Vector2.prototype.negate = function () {
  2464. return new Vector2(-this.x, -this.y);
  2465. };
  2466. /**
  2467. * Multiply the Vector2 coordinates by scale.
  2468. * Returns the updated Vector2.
  2469. */
  2470. Vector2.prototype.scaleInPlace = function (scale) {
  2471. this.x *= scale;
  2472. this.y *= scale;
  2473. return this;
  2474. };
  2475. /**
  2476. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2477. */
  2478. Vector2.prototype.scale = function (scale) {
  2479. var result = new Vector2(0, 0);
  2480. this.scaleToRef(scale, result);
  2481. return result;
  2482. };
  2483. /**
  2484. * Scale the current Vector2 values by a factor to a given Vector2
  2485. * @param scale defines the scale factor
  2486. * @param result defines the Vector2 object where to store the result
  2487. * @returns the unmodified current Vector2
  2488. */
  2489. Vector2.prototype.scaleToRef = function (scale, result) {
  2490. result.x = this.x * scale;
  2491. result.y = this.y * scale;
  2492. return this;
  2493. };
  2494. /**
  2495. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2496. * @param scale defines the scale factor
  2497. * @param result defines the Vector2 object where to store the result
  2498. * @returns the unmodified current Vector2
  2499. */
  2500. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2501. result.x += this.x * scale;
  2502. result.y += this.y * scale;
  2503. return this;
  2504. };
  2505. /**
  2506. * Boolean : True if the given vector coordinates strictly equal the current Vector2 ones.
  2507. */
  2508. Vector2.prototype.equals = function (otherVector) {
  2509. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2510. };
  2511. /**
  2512. * Boolean : True if the given vector coordinates are close to the current ones by a distance of epsilon.
  2513. */
  2514. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2515. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2516. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2517. };
  2518. // Properties
  2519. /**
  2520. * Returns the vector length (float).
  2521. */
  2522. Vector2.prototype.length = function () {
  2523. return Math.sqrt(this.x * this.x + this.y * this.y);
  2524. };
  2525. /**
  2526. * Returns the vector squared length (float);
  2527. */
  2528. Vector2.prototype.lengthSquared = function () {
  2529. return (this.x * this.x + this.y * this.y);
  2530. };
  2531. // Methods
  2532. /**
  2533. * Normalize the vector.
  2534. * Returns the updated Vector2.
  2535. */
  2536. Vector2.prototype.normalize = function () {
  2537. var len = this.length();
  2538. if (len === 0)
  2539. return this;
  2540. var num = 1.0 / len;
  2541. this.x *= num;
  2542. this.y *= num;
  2543. return this;
  2544. };
  2545. /**
  2546. * Returns a new Vector2 copied from the Vector2.
  2547. */
  2548. Vector2.prototype.clone = function () {
  2549. return new Vector2(this.x, this.y);
  2550. };
  2551. // Statics
  2552. /**
  2553. * Returns a new Vector2(0, 0)
  2554. */
  2555. Vector2.Zero = function () {
  2556. return new Vector2(0, 0);
  2557. };
  2558. /**
  2559. * Returns a new Vector2(1, 1)
  2560. */
  2561. Vector2.One = function () {
  2562. return new Vector2(1, 1);
  2563. };
  2564. /**
  2565. * Returns a new Vector2 set from the given index element of the given array.
  2566. */
  2567. Vector2.FromArray = function (array, offset) {
  2568. if (offset === void 0) { offset = 0; }
  2569. return new Vector2(array[offset], array[offset + 1]);
  2570. };
  2571. /**
  2572. * Sets "result" from the given index element of the given array.
  2573. */
  2574. Vector2.FromArrayToRef = function (array, offset, result) {
  2575. result.x = array[offset];
  2576. result.y = array[offset + 1];
  2577. };
  2578. /**
  2579. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2.
  2580. */
  2581. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2582. var squared = amount * amount;
  2583. var cubed = amount * squared;
  2584. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2585. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2586. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2587. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2588. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2589. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2590. return new Vector2(x, y);
  2591. };
  2592. /**
  2593. * 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".
  2594. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2595. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2596. */
  2597. Vector2.Clamp = function (value, min, max) {
  2598. var x = value.x;
  2599. x = (x > max.x) ? max.x : x;
  2600. x = (x < min.x) ? min.x : x;
  2601. var y = value.y;
  2602. y = (y > max.y) ? max.y : y;
  2603. y = (y < min.y) ? min.y : y;
  2604. return new Vector2(x, y);
  2605. };
  2606. /**
  2607. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2608. */
  2609. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2610. var squared = amount * amount;
  2611. var cubed = amount * squared;
  2612. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2613. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2614. var part3 = (cubed - (2.0 * squared)) + amount;
  2615. var part4 = cubed - squared;
  2616. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2617. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2618. return new Vector2(x, y);
  2619. };
  2620. /**
  2621. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2622. */
  2623. Vector2.Lerp = function (start, end, amount) {
  2624. var x = start.x + ((end.x - start.x) * amount);
  2625. var y = start.y + ((end.y - start.y) * amount);
  2626. return new Vector2(x, y);
  2627. };
  2628. /**
  2629. * Returns the dot product (float) of the vector "left" and the vector "right".
  2630. */
  2631. Vector2.Dot = function (left, right) {
  2632. return left.x * right.x + left.y * right.y;
  2633. };
  2634. /**
  2635. * Returns a new Vector2 equal to the normalized given vector.
  2636. */
  2637. Vector2.Normalize = function (vector) {
  2638. var newVector = vector.clone();
  2639. newVector.normalize();
  2640. return newVector;
  2641. };
  2642. /**
  2643. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2644. */
  2645. Vector2.Minimize = function (left, right) {
  2646. var x = (left.x < right.x) ? left.x : right.x;
  2647. var y = (left.y < right.y) ? left.y : right.y;
  2648. return new Vector2(x, y);
  2649. };
  2650. /**
  2651. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2652. */
  2653. Vector2.Maximize = function (left, right) {
  2654. var x = (left.x > right.x) ? left.x : right.x;
  2655. var y = (left.y > right.y) ? left.y : right.y;
  2656. return new Vector2(x, y);
  2657. };
  2658. /**
  2659. * Returns a new Vecto2 set with the transformed coordinates of the given vector by the given transformation matrix.
  2660. */
  2661. Vector2.Transform = function (vector, transformation) {
  2662. var r = Vector2.Zero();
  2663. Vector2.TransformToRef(vector, transformation, r);
  2664. return r;
  2665. };
  2666. /**
  2667. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates.
  2668. */
  2669. Vector2.TransformToRef = function (vector, transformation, result) {
  2670. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2671. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2672. result.x = x;
  2673. result.y = y;
  2674. };
  2675. /**
  2676. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2677. */
  2678. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2679. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2680. var sign = a < 0 ? -1 : 1;
  2681. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2682. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2683. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2684. };
  2685. /**
  2686. * Returns the distance (float) between the vectors "value1" and "value2".
  2687. */
  2688. Vector2.Distance = function (value1, value2) {
  2689. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2690. };
  2691. /**
  2692. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2693. */
  2694. Vector2.DistanceSquared = function (value1, value2) {
  2695. var x = value1.x - value2.x;
  2696. var y = value1.y - value2.y;
  2697. return (x * x) + (y * y);
  2698. };
  2699. /**
  2700. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2701. */
  2702. Vector2.Center = function (value1, value2) {
  2703. var center = value1.add(value2);
  2704. center.scaleInPlace(0.5);
  2705. return center;
  2706. };
  2707. /**
  2708. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2709. */
  2710. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2711. var l2 = Vector2.DistanceSquared(segA, segB);
  2712. if (l2 === 0.0) {
  2713. return Vector2.Distance(p, segA);
  2714. }
  2715. var v = segB.subtract(segA);
  2716. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2717. var proj = segA.add(v.multiplyByFloats(t, t));
  2718. return Vector2.Distance(p, proj);
  2719. };
  2720. return Vector2;
  2721. }());
  2722. BABYLON.Vector2 = Vector2;
  2723. /**
  2724. * Classed used to store (x,y,z) vector representation
  2725. * A Vector3 is the main object used in 3D geometry
  2726. * It can represent etiher the coordinates of a point the space, either a direction
  2727. * Reminder: Babylon.js uses a left handed forward facing system
  2728. */
  2729. var Vector3 = /** @class */ (function () {
  2730. /**
  2731. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2732. * @param x defines the first coordinates (on X axis)
  2733. * @param y defines the second coordinates (on Y axis)
  2734. * @param z defines the third coordinates (on Z axis)
  2735. */
  2736. function Vector3(
  2737. /**
  2738. * Defines the first coordinates (on X axis)
  2739. */
  2740. x,
  2741. /**
  2742. * Defines the second coordinates (on Y axis)
  2743. */
  2744. y,
  2745. /**
  2746. * Defines the third coordinates (on Z axis)
  2747. */
  2748. z) {
  2749. this.x = x;
  2750. this.y = y;
  2751. this.z = z;
  2752. }
  2753. /**
  2754. * Creates a string representation of the Vector3
  2755. * @returns a string with the Vector3 coordinates.
  2756. */
  2757. Vector3.prototype.toString = function () {
  2758. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2759. };
  2760. /**
  2761. * Gets the class name
  2762. * @returns the string "Vector3"
  2763. */
  2764. Vector3.prototype.getClassName = function () {
  2765. return "Vector3";
  2766. };
  2767. /**
  2768. * Creates the Vector3 hash code
  2769. * @returns a number which tends to be unique between Vector3 instances
  2770. */
  2771. Vector3.prototype.getHashCode = function () {
  2772. var hash = this.x || 0;
  2773. hash = (hash * 397) ^ (this.y || 0);
  2774. hash = (hash * 397) ^ (this.z || 0);
  2775. return hash;
  2776. };
  2777. // Operators
  2778. /**
  2779. * Creates an array containing three elements : the coordinates of the Vector3
  2780. * @returns a new array of numbers
  2781. */
  2782. Vector3.prototype.asArray = function () {
  2783. var result = [];
  2784. this.toArray(result, 0);
  2785. return result;
  2786. };
  2787. /**
  2788. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2789. * @param array defines the destination array
  2790. * @param index defines the offset in the destination array
  2791. * @returns the current Vector3
  2792. */
  2793. Vector3.prototype.toArray = function (array, index) {
  2794. if (index === void 0) { index = 0; }
  2795. array[index] = this.x;
  2796. array[index + 1] = this.y;
  2797. array[index + 2] = this.z;
  2798. return this;
  2799. };
  2800. /**
  2801. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2802. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2803. */
  2804. Vector3.prototype.toQuaternion = function () {
  2805. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2806. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2807. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2808. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2809. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2810. var cosy = Math.cos(this.y * 0.5);
  2811. var siny = Math.sin(this.y * 0.5);
  2812. result.x = coszMinusx * siny;
  2813. result.y = -sinzMinusx * siny;
  2814. result.z = sinxPlusz * cosy;
  2815. result.w = cosxPlusz * cosy;
  2816. return result;
  2817. };
  2818. /**
  2819. * Adds the given vector to the current Vector3
  2820. * @param otherVector defines the second operand
  2821. * @returns the current updated Vector3
  2822. */
  2823. Vector3.prototype.addInPlace = function (otherVector) {
  2824. this.x += otherVector.x;
  2825. this.y += otherVector.y;
  2826. this.z += otherVector.z;
  2827. return this;
  2828. };
  2829. /**
  2830. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2831. * @param otherVector defines the second operand
  2832. * @returns the resulting Vector3
  2833. */
  2834. Vector3.prototype.add = function (otherVector) {
  2835. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2836. };
  2837. /**
  2838. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2839. * @param otherVector defines the second operand
  2840. * @param result defines the Vector3 object where to store the result
  2841. * @returns the current Vector3
  2842. */
  2843. Vector3.prototype.addToRef = function (otherVector, result) {
  2844. result.x = this.x + otherVector.x;
  2845. result.y = this.y + otherVector.y;
  2846. result.z = this.z + otherVector.z;
  2847. return this;
  2848. };
  2849. /**
  2850. * Subtract the given vector from the current Vector3
  2851. * @param otherVector defines the second operand
  2852. * @returns the current updated Vector3
  2853. */
  2854. Vector3.prototype.subtractInPlace = function (otherVector) {
  2855. this.x -= otherVector.x;
  2856. this.y -= otherVector.y;
  2857. this.z -= otherVector.z;
  2858. return this;
  2859. };
  2860. /**
  2861. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2862. * @param otherVector defines the second operand
  2863. * @returns the resulting Vector3
  2864. */
  2865. Vector3.prototype.subtract = function (otherVector) {
  2866. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2867. };
  2868. /**
  2869. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2870. * @param otherVector defines the second operand
  2871. * @param result defines the Vector3 object where to store the result
  2872. * @returns the current Vector3
  2873. */
  2874. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2875. result.x = this.x - otherVector.x;
  2876. result.y = this.y - otherVector.y;
  2877. result.z = this.z - otherVector.z;
  2878. return this;
  2879. };
  2880. /**
  2881. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2882. * @param x defines the x coordinate of the operand
  2883. * @param y defines the y coordinate of the operand
  2884. * @param z defines the z coordinate of the operand
  2885. * @returns the resulting Vector3
  2886. */
  2887. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2888. return new Vector3(this.x - x, this.y - y, this.z - z);
  2889. };
  2890. /**
  2891. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2892. * @param x defines the x coordinate of the operand
  2893. * @param y defines the y coordinate of the operand
  2894. * @param z defines the z coordinate of the operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2899. result.x = this.x - x;
  2900. result.y = this.y - y;
  2901. result.z = this.z - z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2906. * @returns a new Vector3
  2907. */
  2908. Vector3.prototype.negate = function () {
  2909. return new Vector3(-this.x, -this.y, -this.z);
  2910. };
  2911. /**
  2912. * Multiplies the Vector3 coordinates by the float "scale"
  2913. * @param scale defines the multiplier factor
  2914. * @returns the current updated Vector3
  2915. */
  2916. Vector3.prototype.scaleInPlace = function (scale) {
  2917. this.x *= scale;
  2918. this.y *= scale;
  2919. this.z *= scale;
  2920. return this;
  2921. };
  2922. /**
  2923. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2924. * @param scale defines the multiplier factor
  2925. * @returns a new Vector3
  2926. */
  2927. Vector3.prototype.scale = function (scale) {
  2928. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2929. };
  2930. /**
  2931. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2932. * @param scale defines the multiplier factor
  2933. * @param result defines the Vector3 object where to store the result
  2934. * @returns the current Vector3
  2935. */
  2936. Vector3.prototype.scaleToRef = function (scale, result) {
  2937. result.x = this.x * scale;
  2938. result.y = this.y * scale;
  2939. result.z = this.z * scale;
  2940. return this;
  2941. };
  2942. /**
  2943. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2944. * @param scale defines the scale factor
  2945. * @param result defines the Vector3 object where to store the result
  2946. * @returns the unmodified current Vector3
  2947. */
  2948. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2949. result.x += this.x * scale;
  2950. result.y += this.y * scale;
  2951. result.z += this.z * scale;
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2956. * @param otherVector defines the second operand
  2957. * @returns true if both vectors are equals
  2958. */
  2959. Vector3.prototype.equals = function (otherVector) {
  2960. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2961. };
  2962. /**
  2963. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2964. * @param otherVector defines the second operand
  2965. * @param epsilon defines the minimal distance to define values as equals
  2966. * @returns true if both vectors are distant less than epsilon
  2967. */
  2968. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2969. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2970. 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);
  2971. };
  2972. /**
  2973. * Returns true if the current Vector3 coordinates equals the given floats
  2974. * @param x defines the x coordinate of the operand
  2975. * @param y defines the y coordinate of the operand
  2976. * @param z defines the z coordinate of the operand
  2977. * @returns true if both vectors are equals
  2978. */
  2979. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2980. return this.x === x && this.y === y && this.z === z;
  2981. };
  2982. /**
  2983. * Multiplies the current Vector3 coordinates by the given ones
  2984. * @param otherVector defines the second operand
  2985. * @returns the current updated Vector3
  2986. */
  2987. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2988. this.x *= otherVector.x;
  2989. this.y *= otherVector.y;
  2990. this.z *= otherVector.z;
  2991. return this;
  2992. };
  2993. /**
  2994. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2995. * @param otherVector defines the second operand
  2996. * @returns the new Vector3
  2997. */
  2998. Vector3.prototype.multiply = function (otherVector) {
  2999. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3000. };
  3001. /**
  3002. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3003. * @param otherVector defines the second operand
  3004. * @param result defines the Vector3 object where to store the result
  3005. * @returns the current Vector3
  3006. */
  3007. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3008. result.x = this.x * otherVector.x;
  3009. result.y = this.y * otherVector.y;
  3010. result.z = this.z * otherVector.z;
  3011. return this;
  3012. };
  3013. /**
  3014. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3015. * @param x defines the x coordinate of the operand
  3016. * @param y defines the y coordinate of the operand
  3017. * @param z defines the z coordinate of the operand
  3018. * @returns the new Vector3
  3019. */
  3020. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3021. return new Vector3(this.x * x, this.y * y, this.z * z);
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3025. * @param otherVector defines the second operand
  3026. * @returns the new Vector3
  3027. */
  3028. Vector3.prototype.divide = function (otherVector) {
  3029. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3030. };
  3031. /**
  3032. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3033. * @param otherVector defines the second operand
  3034. * @param result defines the Vector3 object where to store the result
  3035. * @returns the current Vector3
  3036. */
  3037. Vector3.prototype.divideToRef = function (otherVector, result) {
  3038. result.x = this.x / otherVector.x;
  3039. result.y = this.y / otherVector.y;
  3040. result.z = this.z / otherVector.z;
  3041. return this;
  3042. };
  3043. /**
  3044. * Divides the current Vector3 coordinates by the given ones.
  3045. * @param otherVector defines the second operand
  3046. * @returns the current updated Vector3
  3047. */
  3048. Vector3.prototype.divideInPlace = function (otherVector) {
  3049. return this.divideToRef(otherVector, this);
  3050. };
  3051. /**
  3052. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3053. * @param other defines the second operand
  3054. * @returns the current updated Vector3
  3055. */
  3056. Vector3.prototype.minimizeInPlace = function (other) {
  3057. if (other.x < this.x)
  3058. this.x = other.x;
  3059. if (other.y < this.y)
  3060. this.y = other.y;
  3061. if (other.z < this.z)
  3062. this.z = other.z;
  3063. return this;
  3064. };
  3065. /**
  3066. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3067. * @param other defines the second operand
  3068. * @returns the current updated Vector3
  3069. */
  3070. Vector3.prototype.maximizeInPlace = function (other) {
  3071. if (other.x > this.x)
  3072. this.x = other.x;
  3073. if (other.y > this.y)
  3074. this.y = other.y;
  3075. if (other.z > this.z)
  3076. this.z = other.z;
  3077. return this;
  3078. };
  3079. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3080. /**
  3081. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3082. */
  3083. get: function () {
  3084. var absX = Math.abs(this.x);
  3085. var absY = Math.abs(this.y);
  3086. if (absX !== absY) {
  3087. return true;
  3088. }
  3089. var absZ = Math.abs(this.z);
  3090. if (absX !== absZ) {
  3091. return true;
  3092. }
  3093. if (absY !== absZ) {
  3094. return true;
  3095. }
  3096. return false;
  3097. },
  3098. enumerable: true,
  3099. configurable: true
  3100. });
  3101. // Properties
  3102. /**
  3103. * Gets the length of the Vector3
  3104. * @returns the length of the Vecto3
  3105. */
  3106. Vector3.prototype.length = function () {
  3107. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3108. };
  3109. /**
  3110. * Gets the squared length of the Vector3
  3111. * @returns squared length of the Vector3
  3112. */
  3113. Vector3.prototype.lengthSquared = function () {
  3114. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Normalize the current Vector3.
  3118. * Please note that this is an in place operation.
  3119. * @returns the current updated Vector3
  3120. */
  3121. Vector3.prototype.normalize = function () {
  3122. var len = this.length();
  3123. if (len === 0 || len === 1.0)
  3124. return this;
  3125. var num = 1.0 / len;
  3126. this.x *= num;
  3127. this.y *= num;
  3128. this.z *= num;
  3129. return this;
  3130. };
  3131. /**
  3132. * Normalize the current Vector3 to a new vector
  3133. * @returns the new Vector3
  3134. */
  3135. Vector3.prototype.normalizeToNew = function () {
  3136. var normalized = new Vector3(0, 0, 0);
  3137. this.normalizeToRef(normalized);
  3138. return normalized;
  3139. };
  3140. /**
  3141. * Normalize the current Vector3 to the reference
  3142. * @param reference define the Vector3 to update
  3143. * @returns the updated Vector3
  3144. */
  3145. Vector3.prototype.normalizeToRef = function (reference) {
  3146. var len = this.length();
  3147. if (len === 0 || len === 1.0) {
  3148. reference.set(this.x, this.y, this.z);
  3149. return reference;
  3150. }
  3151. var scale = 1.0 / len;
  3152. this.scaleToRef(scale, reference);
  3153. return reference;
  3154. };
  3155. /**
  3156. * Creates a new Vector3 copied from the current Vector3
  3157. * @returns the new Vector3
  3158. */
  3159. Vector3.prototype.clone = function () {
  3160. return new Vector3(this.x, this.y, this.z);
  3161. };
  3162. /**
  3163. * Copies the given vector coordinates to the current Vector3 ones
  3164. * @param source defines the source Vector3
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.copyFrom = function (source) {
  3168. this.x = source.x;
  3169. this.y = source.y;
  3170. this.z = source.z;
  3171. return this;
  3172. };
  3173. /**
  3174. * Copies the given floats to the current Vector3 coordinates
  3175. * @param x defines the x coordinate of the operand
  3176. * @param y defines the y coordinate of the operand
  3177. * @param z defines the z coordinate of the operand
  3178. * @returns the current updated Vector3
  3179. */
  3180. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3181. this.x = x;
  3182. this.y = y;
  3183. this.z = z;
  3184. return this;
  3185. };
  3186. /**
  3187. * Copies the given floats to the current Vector3 coordinates
  3188. * @param x defines the x coordinate of the operand
  3189. * @param y defines the y coordinate of the operand
  3190. * @param z defines the z coordinate of the operand
  3191. * @returns the current updated Vector3
  3192. */
  3193. Vector3.prototype.set = function (x, y, z) {
  3194. return this.copyFromFloats(x, y, z);
  3195. };
  3196. // Statics
  3197. /**
  3198. * Get the clip factor between two vectors
  3199. * @param vector0 defines the first operand
  3200. * @param vector1 defines the second operand
  3201. * @param axis defines the axis to use
  3202. * @param size defines the size along the axis
  3203. * @returns the clip factor
  3204. */
  3205. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3206. var d0 = Vector3.Dot(vector0, axis) - size;
  3207. var d1 = Vector3.Dot(vector1, axis) - size;
  3208. var s = d0 / (d0 - d1);
  3209. return s;
  3210. };
  3211. /**
  3212. * Get angle between two vectors
  3213. * @param vector0 angle between vector0 and vector1
  3214. * @param vector1 angle between vector0 and vector1
  3215. * @param normal direction of the normal
  3216. * @return the angle between vector0 and vector1
  3217. */
  3218. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3219. var v0 = vector0.clone().normalize();
  3220. var v1 = vector1.clone().normalize();
  3221. var dot = Vector3.Dot(v0, v1);
  3222. var n = Vector3.Cross(v0, v1);
  3223. if (Vector3.Dot(n, normal) > 0) {
  3224. return Math.acos(dot);
  3225. }
  3226. return -Math.acos(dot);
  3227. };
  3228. /**
  3229. * Returns a new Vector3 set from the index "offset" of the given array
  3230. * @param array defines the source array
  3231. * @param offset defines the offset in the source array
  3232. * @returns the new Vector3
  3233. */
  3234. Vector3.FromArray = function (array, offset) {
  3235. if (!offset) {
  3236. offset = 0;
  3237. }
  3238. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3239. };
  3240. /**
  3241. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3242. * This function is deprecated. Use FromArray instead
  3243. * @param array defines the source array
  3244. * @param offset defines the offset in the source array
  3245. * @returns the new Vector3
  3246. */
  3247. Vector3.FromFloatArray = function (array, offset) {
  3248. return Vector3.FromArray(array, offset);
  3249. };
  3250. /**
  3251. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3252. * @param array defines the source array
  3253. * @param offset defines the offset in the source array
  3254. * @param result defines the Vector3 where to store the result
  3255. */
  3256. Vector3.FromArrayToRef = function (array, offset, result) {
  3257. result.x = array[offset];
  3258. result.y = array[offset + 1];
  3259. result.z = array[offset + 2];
  3260. };
  3261. /**
  3262. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3263. * This function is deprecated. Use FromArrayToRef instead.
  3264. * @param array defines the source array
  3265. * @param offset defines the offset in the source array
  3266. * @param result defines the Vector3 where to store the result
  3267. */
  3268. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3269. return Vector3.FromArrayToRef(array, offset, result);
  3270. };
  3271. /**
  3272. * Sets the given vector "result" with the given floats.
  3273. * @param x defines the x coordinate of the source
  3274. * @param y defines the y coordinate of the source
  3275. * @param z defines the z coordinate of the source
  3276. * @param result defines the Vector3 where to store the result
  3277. */
  3278. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3279. result.x = x;
  3280. result.y = y;
  3281. result.z = z;
  3282. };
  3283. /**
  3284. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3285. * @returns a new empty Vector3
  3286. */
  3287. Vector3.Zero = function () {
  3288. return new Vector3(0.0, 0.0, 0.0);
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3292. * @returns a new unit Vector3
  3293. */
  3294. Vector3.One = function () {
  3295. return new Vector3(1.0, 1.0, 1.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3299. * @returns a new up Vector3
  3300. */
  3301. Vector3.Up = function () {
  3302. return new Vector3(0.0, 1.0, 0.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3306. * @returns a new forward Vector3
  3307. */
  3308. Vector3.Forward = function () {
  3309. return new Vector3(0.0, 0.0, 1.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3313. * @returns a new right Vector3
  3314. */
  3315. Vector3.Right = function () {
  3316. return new Vector3(1.0, 0.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3320. * @returns a new left Vector3
  3321. */
  3322. Vector3.Left = function () {
  3323. return new Vector3(-1.0, 0.0, 0.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3327. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3328. * @param vector defines the Vector3 to transform
  3329. * @param transformation defines the transformation matrix
  3330. * @returns the transformed Vector3
  3331. */
  3332. Vector3.TransformCoordinates = function (vector, transformation) {
  3333. var result = Vector3.Zero();
  3334. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3335. return result;
  3336. };
  3337. /**
  3338. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3339. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3340. * @param vector defines the Vector3 to transform
  3341. * @param transformation defines the transformation matrix
  3342. * @param result defines the Vector3 where to store the result
  3343. */
  3344. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3345. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3346. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3347. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3348. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3349. result.x = x / w;
  3350. result.y = y / w;
  3351. result.z = z / w;
  3352. };
  3353. /**
  3354. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3355. * This method computes tranformed coordinates only, not transformed direction vectors
  3356. * @param x define the x coordinate of the source vector
  3357. * @param y define the y coordinate of the source vector
  3358. * @param z define the z coordinate of the source vector
  3359. * @param transformation defines the transformation matrix
  3360. * @param result defines the Vector3 where to store the result
  3361. */
  3362. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3363. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3364. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3365. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3366. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3367. result.x = rx / rw;
  3368. result.y = ry / rw;
  3369. result.z = rz / rw;
  3370. };
  3371. /**
  3372. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3373. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3374. * @param vector defines the Vector3 to transform
  3375. * @param transformation defines the transformation matrix
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.TransformNormal = function (vector, transformation) {
  3379. var result = Vector3.Zero();
  3380. Vector3.TransformNormalToRef(vector, transformation, result);
  3381. return result;
  3382. };
  3383. /**
  3384. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3385. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3386. * @param vector defines the Vector3 to transform
  3387. * @param transformation defines the transformation matrix
  3388. * @param result defines the Vector3 where to store the result
  3389. */
  3390. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3391. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3392. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3393. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3394. result.x = x;
  3395. result.y = y;
  3396. result.z = z;
  3397. };
  3398. /**
  3399. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3400. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3401. * @param x define the x coordinate of the source vector
  3402. * @param y define the y coordinate of the source vector
  3403. * @param z define the z coordinate of the source vector
  3404. * @param transformation defines the transformation matrix
  3405. * @param result defines the Vector3 where to store the result
  3406. */
  3407. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3408. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3409. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3410. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3414. * @param value1 defines the first control point
  3415. * @param value2 defines the second control point
  3416. * @param value3 defines the third control point
  3417. * @param value4 defines the fourth control point
  3418. * @param amount defines the amount on the spline to use
  3419. * @returns the new Vector3
  3420. */
  3421. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3422. var squared = amount * amount;
  3423. var cubed = amount * squared;
  3424. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3425. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3426. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3427. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3428. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3429. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3430. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3431. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3432. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3433. return new Vector3(x, y, z);
  3434. };
  3435. /**
  3436. * 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"
  3437. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3438. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3439. * @param value defines the current value
  3440. * @param min defines the lower range value
  3441. * @param max defines the upper range value
  3442. * @returns the new Vector3
  3443. */
  3444. Vector3.Clamp = function (value, min, max) {
  3445. var x = value.x;
  3446. x = (x > max.x) ? max.x : x;
  3447. x = (x < min.x) ? min.x : x;
  3448. var y = value.y;
  3449. y = (y > max.y) ? max.y : y;
  3450. y = (y < min.y) ? min.y : y;
  3451. var z = value.z;
  3452. z = (z > max.z) ? max.z : z;
  3453. z = (z < min.z) ? min.z : z;
  3454. return new Vector3(x, y, z);
  3455. };
  3456. /**
  3457. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3458. * @param value1 defines the first control point
  3459. * @param tangent1 defines the first tangent vector
  3460. * @param value2 defines the second control point
  3461. * @param tangent2 defines the second tangent vector
  3462. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3463. * @returns the new Vector3
  3464. */
  3465. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3466. var squared = amount * amount;
  3467. var cubed = amount * squared;
  3468. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3469. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3470. var part3 = (cubed - (2.0 * squared)) + amount;
  3471. var part4 = cubed - squared;
  3472. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3473. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3474. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3475. return new Vector3(x, y, z);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3479. * @param start defines the start value
  3480. * @param end defines the end value
  3481. * @param amount max defines amount between both (between 0 and 1)
  3482. * @returns the new Vector3
  3483. */
  3484. Vector3.Lerp = function (start, end, amount) {
  3485. var result = new Vector3(0, 0, 0);
  3486. Vector3.LerpToRef(start, end, amount, result);
  3487. return result;
  3488. };
  3489. /**
  3490. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3491. * @param start defines the start value
  3492. * @param end defines the end value
  3493. * @param amount max defines amount between both (between 0 and 1)
  3494. * @param result defines the Vector3 where to store the result
  3495. */
  3496. Vector3.LerpToRef = function (start, end, amount, result) {
  3497. result.x = start.x + ((end.x - start.x) * amount);
  3498. result.y = start.y + ((end.y - start.y) * amount);
  3499. result.z = start.z + ((end.z - start.z) * amount);
  3500. };
  3501. /**
  3502. * Returns the dot product (float) between the vectors "left" and "right"
  3503. * @param left defines the left operand
  3504. * @param right defines the right operand
  3505. * @returns the dot product
  3506. */
  3507. Vector3.Dot = function (left, right) {
  3508. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3509. };
  3510. /**
  3511. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3512. * The cross product is then orthogonal to both "left" and "right"
  3513. * @param left defines the left operand
  3514. * @param right defines the right operand
  3515. * @returns the cross product
  3516. */
  3517. Vector3.Cross = function (left, right) {
  3518. var result = Vector3.Zero();
  3519. Vector3.CrossToRef(left, right, result);
  3520. return result;
  3521. };
  3522. /**
  3523. * Sets the given vector "result" with the cross product of "left" and "right"
  3524. * The cross product is then orthogonal to both "left" and "right"
  3525. * @param left defines the left operand
  3526. * @param right defines the right operand
  3527. * @param result defines the Vector3 where to store the result
  3528. */
  3529. Vector3.CrossToRef = function (left, right, result) {
  3530. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3531. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3532. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3533. result.copyFrom(MathTmp.Vector3[0]);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 as the normalization of the given vector
  3537. * @param vector defines the Vector3 to normalize
  3538. * @returns the new Vector3
  3539. */
  3540. Vector3.Normalize = function (vector) {
  3541. var result = Vector3.Zero();
  3542. Vector3.NormalizeToRef(vector, result);
  3543. return result;
  3544. };
  3545. /**
  3546. * Sets the given vector "result" with the normalization of the given first vector
  3547. * @param vector defines the Vector3 to normalize
  3548. * @param result defines the Vector3 where to store the result
  3549. */
  3550. Vector3.NormalizeToRef = function (vector, result) {
  3551. result.copyFrom(vector);
  3552. result.normalize();
  3553. };
  3554. /**
  3555. * Project a Vector3 onto screen space
  3556. * @param vector defines the Vector3 to project
  3557. * @param world defines the world matrix to use
  3558. * @param transform defines the transform (view x projection) matrix to use
  3559. * @param viewport defines the screen viewport to use
  3560. * @returns the new Vector3
  3561. */
  3562. Vector3.Project = function (vector, world, transform, viewport) {
  3563. var cw = viewport.width;
  3564. var ch = viewport.height;
  3565. var cx = viewport.x;
  3566. var cy = viewport.y;
  3567. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3568. 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);
  3569. var matrix = MathTmp.Matrix[0];
  3570. world.multiplyToRef(transform, matrix);
  3571. matrix.multiplyToRef(viewportMatrix, matrix);
  3572. return Vector3.TransformCoordinates(vector, matrix);
  3573. };
  3574. /**
  3575. * Unproject from screen space to object space
  3576. * @param source defines the screen space Vector3 to use
  3577. * @param viewportWidth defines the current width of the viewport
  3578. * @param viewportHeight defines the current height of the viewport
  3579. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3580. * @param transform defines the transform (view x projection) matrix to use
  3581. * @returns the new Vector3
  3582. */
  3583. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3584. var matrix = MathTmp.Matrix[0];
  3585. world.multiplyToRef(transform, matrix);
  3586. matrix.invert();
  3587. source.x = source.x / viewportWidth * 2 - 1;
  3588. source.y = -(source.y / viewportHeight * 2 - 1);
  3589. var vector = Vector3.TransformCoordinates(source, matrix);
  3590. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3591. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3592. vector = vector.scale(1.0 / num);
  3593. }
  3594. return vector;
  3595. };
  3596. /**
  3597. * Unproject from screen space to object space
  3598. * @param source defines the screen space Vector3 to use
  3599. * @param viewportWidth defines the current width of the viewport
  3600. * @param viewportHeight defines the current height of the viewport
  3601. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3602. * @param view defines the view matrix to use
  3603. * @param projection defines the projection matrix to use
  3604. * @returns the new Vector3
  3605. */
  3606. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3607. var result = Vector3.Zero();
  3608. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3609. return result;
  3610. };
  3611. /**
  3612. * Unproject from screen space to object space
  3613. * @param source defines the screen space Vector3 to use
  3614. * @param viewportWidth defines the current width of the viewport
  3615. * @param viewportHeight defines the current height of the viewport
  3616. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3617. * @param view defines the view matrix to use
  3618. * @param projection defines the projection matrix to use
  3619. * @param result defines the Vector3 where to store the result
  3620. */
  3621. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3622. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3623. };
  3624. /**
  3625. * Unproject from screen space to object space
  3626. * @param sourceX defines the screen space x coordinate to use
  3627. * @param sourceY defines the screen space y coordinate to use
  3628. * @param sourceZ defines the screen space z coordinate to use
  3629. * @param viewportWidth defines the current width of the viewport
  3630. * @param viewportHeight defines the current height of the viewport
  3631. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3632. * @param view defines the view matrix to use
  3633. * @param projection defines the projection matrix to use
  3634. * @param result defines the Vector3 where to store the result
  3635. */
  3636. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3637. var matrix = MathTmp.Matrix[0];
  3638. world.multiplyToRef(view, matrix);
  3639. matrix.multiplyToRef(projection, matrix);
  3640. matrix.invert();
  3641. var screenSource = MathTmp.Vector3[0];
  3642. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3643. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3644. screenSource.z = 2 * sourceZ - 1.0;
  3645. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3646. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3647. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3648. result.scaleInPlace(1.0 / num);
  3649. }
  3650. };
  3651. /**
  3652. * Gets the minimal coordinate values between two Vector3
  3653. * @param left defines the first operand
  3654. * @param right defines the second operand
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Minimize = function (left, right) {
  3658. var min = left.clone();
  3659. min.minimizeInPlace(right);
  3660. return min;
  3661. };
  3662. /**
  3663. * Gets the maximal coordinate values between two Vector3
  3664. * @param left defines the first operand
  3665. * @param right defines the second operand
  3666. * @returns the new Vector3
  3667. */
  3668. Vector3.Maximize = function (left, right) {
  3669. var max = left.clone();
  3670. max.maximizeInPlace(right);
  3671. return max;
  3672. };
  3673. /**
  3674. * Returns the distance between the vectors "value1" and "value2"
  3675. * @param value1 defines the first operand
  3676. * @param value2 defines the second operand
  3677. * @returns the distance
  3678. */
  3679. Vector3.Distance = function (value1, value2) {
  3680. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3681. };
  3682. /**
  3683. * Returns the squared distance between the vectors "value1" and "value2"
  3684. * @param value1 defines the first operand
  3685. * @param value2 defines the second operand
  3686. * @returns the squared distance
  3687. */
  3688. Vector3.DistanceSquared = function (value1, value2) {
  3689. var x = value1.x - value2.x;
  3690. var y = value1.y - value2.y;
  3691. var z = value1.z - value2.z;
  3692. return (x * x) + (y * y) + (z * z);
  3693. };
  3694. /**
  3695. * Returns a new Vector3 located at the center between "value1" and "value2"
  3696. * @param value1 defines the first operand
  3697. * @param value2 defines the second operand
  3698. * @returns the new Vector3
  3699. */
  3700. Vector3.Center = function (value1, value2) {
  3701. var center = value1.add(value2);
  3702. center.scaleInPlace(0.5);
  3703. return center;
  3704. };
  3705. /**
  3706. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3707. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3708. * to something in order to rotate it from its local system to the given target system
  3709. * Note: axis1, axis2 and axis3 are normalized during this operation
  3710. * @param axis1 defines the first axis
  3711. * @param axis2 defines the second axis
  3712. * @param axis3 defines the third axis
  3713. * @returns a new Vector3
  3714. */
  3715. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3716. var rotation = Vector3.Zero();
  3717. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3718. return rotation;
  3719. };
  3720. /**
  3721. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3722. * @param axis1 defines the first axis
  3723. * @param axis2 defines the second axis
  3724. * @param axis3 defines the third axis
  3725. * @param ref defines the Vector3 where to store the result
  3726. */
  3727. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3728. var quat = MathTmp.Quaternion[0];
  3729. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3730. quat.toEulerAnglesToRef(ref);
  3731. };
  3732. return Vector3;
  3733. }());
  3734. BABYLON.Vector3 = Vector3;
  3735. //Vector4 class created for EulerAngle class conversion to Quaternion
  3736. var Vector4 = /** @class */ (function () {
  3737. /**
  3738. * Creates a Vector4 object from the given floats.
  3739. */
  3740. function Vector4(x, y, z, w) {
  3741. this.x = x;
  3742. this.y = y;
  3743. this.z = z;
  3744. this.w = w;
  3745. }
  3746. /**
  3747. * Returns the string with the Vector4 coordinates.
  3748. */
  3749. Vector4.prototype.toString = function () {
  3750. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3751. };
  3752. /**
  3753. * Returns the string "Vector4".
  3754. */
  3755. Vector4.prototype.getClassName = function () {
  3756. return "Vector4";
  3757. };
  3758. /**
  3759. * Returns the Vector4 hash code.
  3760. */
  3761. Vector4.prototype.getHashCode = function () {
  3762. var hash = this.x || 0;
  3763. hash = (hash * 397) ^ (this.y || 0);
  3764. hash = (hash * 397) ^ (this.z || 0);
  3765. hash = (hash * 397) ^ (this.w || 0);
  3766. return hash;
  3767. };
  3768. // Operators
  3769. /**
  3770. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3771. */
  3772. Vector4.prototype.asArray = function () {
  3773. var result = new Array();
  3774. this.toArray(result, 0);
  3775. return result;
  3776. };
  3777. /**
  3778. * Populates the given array from the given index with the Vector4 coordinates.
  3779. * Returns the Vector4.
  3780. */
  3781. Vector4.prototype.toArray = function (array, index) {
  3782. if (index === undefined) {
  3783. index = 0;
  3784. }
  3785. array[index] = this.x;
  3786. array[index + 1] = this.y;
  3787. array[index + 2] = this.z;
  3788. array[index + 3] = this.w;
  3789. return this;
  3790. };
  3791. /**
  3792. * Adds the given vector to the current Vector4.
  3793. * Returns the updated Vector4.
  3794. */
  3795. Vector4.prototype.addInPlace = function (otherVector) {
  3796. this.x += otherVector.x;
  3797. this.y += otherVector.y;
  3798. this.z += otherVector.z;
  3799. this.w += otherVector.w;
  3800. return this;
  3801. };
  3802. /**
  3803. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3804. */
  3805. Vector4.prototype.add = function (otherVector) {
  3806. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3807. };
  3808. /**
  3809. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3810. * Returns the current Vector4.
  3811. */
  3812. Vector4.prototype.addToRef = function (otherVector, result) {
  3813. result.x = this.x + otherVector.x;
  3814. result.y = this.y + otherVector.y;
  3815. result.z = this.z + otherVector.z;
  3816. result.w = this.w + otherVector.w;
  3817. return this;
  3818. };
  3819. /**
  3820. * Subtract in place the given vector from the current Vector4.
  3821. * Returns the updated Vector4.
  3822. */
  3823. Vector4.prototype.subtractInPlace = function (otherVector) {
  3824. this.x -= otherVector.x;
  3825. this.y -= otherVector.y;
  3826. this.z -= otherVector.z;
  3827. this.w -= otherVector.w;
  3828. return this;
  3829. };
  3830. /**
  3831. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3832. */
  3833. Vector4.prototype.subtract = function (otherVector) {
  3834. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3835. };
  3836. /**
  3837. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3838. * Returns the current Vector4.
  3839. */
  3840. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3841. result.x = this.x - otherVector.x;
  3842. result.y = this.y - otherVector.y;
  3843. result.z = this.z - otherVector.z;
  3844. result.w = this.w - otherVector.w;
  3845. return this;
  3846. };
  3847. /**
  3848. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3849. */
  3850. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3851. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3852. };
  3853. /**
  3854. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3855. * Returns the current Vector4.
  3856. */
  3857. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3858. result.x = this.x - x;
  3859. result.y = this.y - y;
  3860. result.z = this.z - z;
  3861. result.w = this.w - w;
  3862. return this;
  3863. };
  3864. /**
  3865. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3866. */
  3867. Vector4.prototype.negate = function () {
  3868. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3869. };
  3870. /**
  3871. * Multiplies the current Vector4 coordinates by scale (float).
  3872. * Returns the updated Vector4.
  3873. */
  3874. Vector4.prototype.scaleInPlace = function (scale) {
  3875. this.x *= scale;
  3876. this.y *= scale;
  3877. this.z *= scale;
  3878. this.w *= scale;
  3879. return this;
  3880. };
  3881. /**
  3882. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3883. */
  3884. Vector4.prototype.scale = function (scale) {
  3885. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3886. };
  3887. /**
  3888. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3889. * Returns the current Vector4.
  3890. */
  3891. Vector4.prototype.scaleToRef = function (scale, result) {
  3892. result.x = this.x * scale;
  3893. result.y = this.y * scale;
  3894. result.z = this.z * scale;
  3895. result.w = this.w * scale;
  3896. return this;
  3897. };
  3898. /**
  3899. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3900. * @param scale defines the scale factor
  3901. * @param result defines the Vector4 object where to store the result
  3902. * @returns the unmodified current Vector4
  3903. */
  3904. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3905. result.x += this.x * scale;
  3906. result.y += this.y * scale;
  3907. result.z += this.z * scale;
  3908. result.w += this.w * scale;
  3909. return this;
  3910. };
  3911. /**
  3912. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3913. */
  3914. Vector4.prototype.equals = function (otherVector) {
  3915. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3916. };
  3917. /**
  3918. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3919. */
  3920. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3921. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3922. return otherVector
  3923. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3924. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3925. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3926. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3927. };
  3928. /**
  3929. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3930. */
  3931. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3932. return this.x === x && this.y === y && this.z === z && this.w === w;
  3933. };
  3934. /**
  3935. * Multiplies in place the current Vector4 by the given one.
  3936. * Returns the updated Vector4.
  3937. */
  3938. Vector4.prototype.multiplyInPlace = 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 set with the multiplication result of the current Vector4 and the given one.
  3947. */
  3948. Vector4.prototype.multiply = 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. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3953. * Returns the current Vector4.
  3954. */
  3955. Vector4.prototype.multiplyToRef = 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 multiplication result of the given floats and the current Vector4 coordinates.
  3964. */
  3965. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3966. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3967. };
  3968. /**
  3969. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3970. */
  3971. Vector4.prototype.divide = function (otherVector) {
  3972. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3973. };
  3974. /**
  3975. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3976. * Returns the current Vector4.
  3977. */
  3978. Vector4.prototype.divideToRef = function (otherVector, result) {
  3979. result.x = this.x / otherVector.x;
  3980. result.y = this.y / otherVector.y;
  3981. result.z = this.z / otherVector.z;
  3982. result.w = this.w / otherVector.w;
  3983. return this;
  3984. };
  3985. /**
  3986. * Divides the current Vector3 coordinates by the given ones.
  3987. * @returns the updated Vector3.
  3988. */
  3989. Vector4.prototype.divideInPlace = function (otherVector) {
  3990. return this.divideToRef(otherVector, this);
  3991. };
  3992. /**
  3993. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3994. * @param other defines the second operand
  3995. * @returns the current updated Vector4
  3996. */
  3997. Vector4.prototype.minimizeInPlace = function (other) {
  3998. if (other.x < this.x)
  3999. this.x = other.x;
  4000. if (other.y < this.y)
  4001. this.y = other.y;
  4002. if (other.z < this.z)
  4003. this.z = other.z;
  4004. if (other.w < this.w)
  4005. this.w = other.w;
  4006. return this;
  4007. };
  4008. /**
  4009. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4010. * @param other defines the second operand
  4011. * @returns the current updated Vector4
  4012. */
  4013. Vector4.prototype.maximizeInPlace = function (other) {
  4014. if (other.x > this.x)
  4015. this.x = other.x;
  4016. if (other.y > this.y)
  4017. this.y = other.y;
  4018. if (other.z > this.z)
  4019. this.z = other.z;
  4020. if (other.w > this.w)
  4021. this.w = other.w;
  4022. return this;
  4023. };
  4024. // Properties
  4025. /**
  4026. * Returns the Vector4 length (float).
  4027. */
  4028. Vector4.prototype.length = function () {
  4029. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4030. };
  4031. /**
  4032. * Returns the Vector4 squared length (float).
  4033. */
  4034. Vector4.prototype.lengthSquared = function () {
  4035. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4036. };
  4037. // Methods
  4038. /**
  4039. * Normalizes in place the Vector4.
  4040. * Returns the updated Vector4.
  4041. */
  4042. Vector4.prototype.normalize = function () {
  4043. var len = this.length();
  4044. if (len === 0)
  4045. return this;
  4046. var num = 1.0 / len;
  4047. this.x *= num;
  4048. this.y *= num;
  4049. this.z *= num;
  4050. this.w *= num;
  4051. return this;
  4052. };
  4053. /**
  4054. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4055. */
  4056. Vector4.prototype.toVector3 = function () {
  4057. return new Vector3(this.x, this.y, this.z);
  4058. };
  4059. /**
  4060. * Returns a new Vector4 copied from the current one.
  4061. */
  4062. Vector4.prototype.clone = function () {
  4063. return new Vector4(this.x, this.y, this.z, this.w);
  4064. };
  4065. /**
  4066. * Updates the current Vector4 with the given one coordinates.
  4067. * Returns the updated Vector4.
  4068. */
  4069. Vector4.prototype.copyFrom = function (source) {
  4070. this.x = source.x;
  4071. this.y = source.y;
  4072. this.z = source.z;
  4073. this.w = source.w;
  4074. return this;
  4075. };
  4076. /**
  4077. * Updates the current Vector4 coordinates with the given floats.
  4078. * Returns the updated Vector4.
  4079. */
  4080. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4081. this.x = x;
  4082. this.y = y;
  4083. this.z = z;
  4084. this.w = w;
  4085. return this;
  4086. };
  4087. /**
  4088. * Updates the current Vector4 coordinates with the given floats.
  4089. * Returns the updated Vector4.
  4090. */
  4091. Vector4.prototype.set = function (x, y, z, w) {
  4092. return this.copyFromFloats(x, y, z, w);
  4093. };
  4094. // Statics
  4095. /**
  4096. * Returns a new Vector4 set from the starting index of the given array.
  4097. */
  4098. Vector4.FromArray = function (array, offset) {
  4099. if (!offset) {
  4100. offset = 0;
  4101. }
  4102. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4103. };
  4104. /**
  4105. * Updates the given vector "result" from the starting index of the given array.
  4106. */
  4107. Vector4.FromArrayToRef = function (array, offset, result) {
  4108. result.x = array[offset];
  4109. result.y = array[offset + 1];
  4110. result.z = array[offset + 2];
  4111. result.w = array[offset + 3];
  4112. };
  4113. /**
  4114. * Updates the given vector "result" from the starting index of the given Float32Array.
  4115. */
  4116. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4117. Vector4.FromArrayToRef(array, offset, result);
  4118. };
  4119. /**
  4120. * Updates the given vector "result" coordinates from the given floats.
  4121. */
  4122. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4123. result.x = x;
  4124. result.y = y;
  4125. result.z = z;
  4126. result.w = w;
  4127. };
  4128. /**
  4129. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4130. */
  4131. Vector4.Zero = function () {
  4132. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4133. };
  4134. /**
  4135. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4136. */
  4137. Vector4.One = function () {
  4138. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4139. };
  4140. /**
  4141. * Returns a new normalized Vector4 from the given one.
  4142. */
  4143. Vector4.Normalize = function (vector) {
  4144. var result = Vector4.Zero();
  4145. Vector4.NormalizeToRef(vector, result);
  4146. return result;
  4147. };
  4148. /**
  4149. * Updates the given vector "result" from the normalization of the given one.
  4150. */
  4151. Vector4.NormalizeToRef = function (vector, result) {
  4152. result.copyFrom(vector);
  4153. result.normalize();
  4154. };
  4155. Vector4.Minimize = function (left, right) {
  4156. var min = left.clone();
  4157. min.minimizeInPlace(right);
  4158. return min;
  4159. };
  4160. Vector4.Maximize = function (left, right) {
  4161. var max = left.clone();
  4162. max.maximizeInPlace(right);
  4163. return max;
  4164. };
  4165. /**
  4166. * Returns the distance (float) between the vectors "value1" and "value2".
  4167. */
  4168. Vector4.Distance = function (value1, value2) {
  4169. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4170. };
  4171. /**
  4172. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4173. */
  4174. Vector4.DistanceSquared = function (value1, value2) {
  4175. var x = value1.x - value2.x;
  4176. var y = value1.y - value2.y;
  4177. var z = value1.z - value2.z;
  4178. var w = value1.w - value2.w;
  4179. return (x * x) + (y * y) + (z * z) + (w * w);
  4180. };
  4181. /**
  4182. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4183. */
  4184. Vector4.Center = function (value1, value2) {
  4185. var center = value1.add(value2);
  4186. center.scaleInPlace(0.5);
  4187. return center;
  4188. };
  4189. /**
  4190. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4191. * This methods computes transformed normalized direction vectors only.
  4192. */
  4193. Vector4.TransformNormal = function (vector, transformation) {
  4194. var result = Vector4.Zero();
  4195. Vector4.TransformNormalToRef(vector, transformation, result);
  4196. return result;
  4197. };
  4198. /**
  4199. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4200. * This methods computes transformed normalized direction vectors only.
  4201. */
  4202. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4203. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4204. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4205. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4206. result.x = x;
  4207. result.y = y;
  4208. result.z = z;
  4209. result.w = vector.w;
  4210. };
  4211. /**
  4212. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4213. * This methods computes transformed normalized direction vectors only.
  4214. */
  4215. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4216. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4217. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4218. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4219. result.w = w;
  4220. };
  4221. return Vector4;
  4222. }());
  4223. BABYLON.Vector4 = Vector4;
  4224. var Size = /** @class */ (function () {
  4225. /**
  4226. * Creates a Size object from the given width and height (floats).
  4227. */
  4228. function Size(width, height) {
  4229. this.width = width;
  4230. this.height = height;
  4231. }
  4232. // Returns a string with the Size width and height.
  4233. Size.prototype.toString = function () {
  4234. return "{W: " + this.width + ", H: " + this.height + "}";
  4235. };
  4236. /**
  4237. * Returns the string "Size"
  4238. */
  4239. Size.prototype.getClassName = function () {
  4240. return "Size";
  4241. };
  4242. /**
  4243. * Returns the Size hash code.
  4244. */
  4245. Size.prototype.getHashCode = function () {
  4246. var hash = this.width || 0;
  4247. hash = (hash * 397) ^ (this.height || 0);
  4248. return hash;
  4249. };
  4250. /**
  4251. * Updates the current size from the given one.
  4252. * Returns the updated Size.
  4253. */
  4254. Size.prototype.copyFrom = function (src) {
  4255. this.width = src.width;
  4256. this.height = src.height;
  4257. };
  4258. /**
  4259. * Updates in place the current Size from the given floats.
  4260. * Returns the updated Size.
  4261. */
  4262. Size.prototype.copyFromFloats = function (width, height) {
  4263. this.width = width;
  4264. this.height = height;
  4265. return this;
  4266. };
  4267. /**
  4268. * Updates in place the current Size from the given floats.
  4269. * Returns the updated Size.
  4270. */
  4271. Size.prototype.set = function (width, height) {
  4272. return this.copyFromFloats(width, height);
  4273. };
  4274. /**
  4275. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4276. */
  4277. Size.prototype.multiplyByFloats = function (w, h) {
  4278. return new Size(this.width * w, this.height * h);
  4279. };
  4280. /**
  4281. * Returns a new Size copied from the given one.
  4282. */
  4283. Size.prototype.clone = function () {
  4284. return new Size(this.width, this.height);
  4285. };
  4286. /**
  4287. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4288. */
  4289. Size.prototype.equals = function (other) {
  4290. if (!other) {
  4291. return false;
  4292. }
  4293. return (this.width === other.width) && (this.height === other.height);
  4294. };
  4295. Object.defineProperty(Size.prototype, "surface", {
  4296. /**
  4297. * Returns the surface of the Size : width * height (float).
  4298. */
  4299. get: function () {
  4300. return this.width * this.height;
  4301. },
  4302. enumerable: true,
  4303. configurable: true
  4304. });
  4305. /**
  4306. * Returns a new Size set to (0.0, 0.0)
  4307. */
  4308. Size.Zero = function () {
  4309. return new Size(0.0, 0.0);
  4310. };
  4311. /**
  4312. * Returns a new Size set as the addition result of the current Size and the given one.
  4313. */
  4314. Size.prototype.add = function (otherSize) {
  4315. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4316. return r;
  4317. };
  4318. /**
  4319. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4320. */
  4321. Size.prototype.subtract = function (otherSize) {
  4322. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4323. return r;
  4324. };
  4325. /**
  4326. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4327. */
  4328. Size.Lerp = function (start, end, amount) {
  4329. var w = start.width + ((end.width - start.width) * amount);
  4330. var h = start.height + ((end.height - start.height) * amount);
  4331. return new Size(w, h);
  4332. };
  4333. return Size;
  4334. }());
  4335. BABYLON.Size = Size;
  4336. /**
  4337. * Class used to store quaternion data
  4338. * @see https://en.wikipedia.org/wiki/Quaternion
  4339. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4340. */
  4341. var Quaternion = /** @class */ (function () {
  4342. /**
  4343. * Creates a new Quaternion from the given floats
  4344. * @param x defines the first component (0 by default)
  4345. * @param y defines the second component (0 by default)
  4346. * @param z defines the third component (0 by default)
  4347. * @param w defines the fourth component (1.0 by default)
  4348. */
  4349. function Quaternion(
  4350. /** defines the first component (0 by default) */
  4351. x,
  4352. /** defines the second component (0 by default) */
  4353. y,
  4354. /** defines the third component (0 by default) */
  4355. z,
  4356. /** defines the fourth component (1.0 by default) */
  4357. w) {
  4358. if (x === void 0) { x = 0.0; }
  4359. if (y === void 0) { y = 0.0; }
  4360. if (z === void 0) { z = 0.0; }
  4361. if (w === void 0) { w = 1.0; }
  4362. this.x = x;
  4363. this.y = y;
  4364. this.z = z;
  4365. this.w = w;
  4366. }
  4367. /**
  4368. * Gets a string representation for the current quaternion
  4369. * @returns a string with the Quaternion coordinates
  4370. */
  4371. Quaternion.prototype.toString = function () {
  4372. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4373. };
  4374. /**
  4375. * Gets the class name of the quaternion
  4376. * @returns the string "Quaternion"
  4377. */
  4378. Quaternion.prototype.getClassName = function () {
  4379. return "Quaternion";
  4380. };
  4381. /**
  4382. * Gets a hash code for this quaternion
  4383. * @returns the quaternion hash code
  4384. */
  4385. Quaternion.prototype.getHashCode = function () {
  4386. var hash = this.x || 0;
  4387. hash = (hash * 397) ^ (this.y || 0);
  4388. hash = (hash * 397) ^ (this.z || 0);
  4389. hash = (hash * 397) ^ (this.w || 0);
  4390. return hash;
  4391. };
  4392. /**
  4393. * Copy the quaternion to an array
  4394. * @returns a new array populated with 4 elements from the quaternion coordinates
  4395. */
  4396. Quaternion.prototype.asArray = function () {
  4397. return [this.x, this.y, this.z, this.w];
  4398. };
  4399. /**
  4400. * Check if two quaternions are equals
  4401. * @param otherQuaternion defines the second operand
  4402. * @return true if the current quaternion and the given one coordinates are strictly equals
  4403. */
  4404. Quaternion.prototype.equals = function (otherQuaternion) {
  4405. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4406. };
  4407. /**
  4408. * Clone the current quaternion
  4409. * @returns a new quaternion copied from the current one
  4410. */
  4411. Quaternion.prototype.clone = function () {
  4412. return new Quaternion(this.x, this.y, this.z, this.w);
  4413. };
  4414. /**
  4415. * Copy a quaternion to the current one
  4416. * @param other defines the other quaternion
  4417. * @returns the updated current quaternion
  4418. */
  4419. Quaternion.prototype.copyFrom = function (other) {
  4420. this.x = other.x;
  4421. this.y = other.y;
  4422. this.z = other.z;
  4423. this.w = other.w;
  4424. return this;
  4425. };
  4426. /**
  4427. * Updates the current quaternion with the given float coordinates
  4428. * @param x defines the x coordinate
  4429. * @param y defines the y coordinate
  4430. * @param z defines the z coordinate
  4431. * @param w defines the w coordinate
  4432. * @returns the updated current quaternion
  4433. */
  4434. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4435. this.x = x;
  4436. this.y = y;
  4437. this.z = z;
  4438. this.w = w;
  4439. return this;
  4440. };
  4441. /**
  4442. * Updates the current quaternion from the given float coordinates
  4443. * @param x defines the x coordinate
  4444. * @param y defines the y coordinate
  4445. * @param z defines the z coordinate
  4446. * @param w defines the w coordinate
  4447. * @returns the updated current quaternion
  4448. */
  4449. Quaternion.prototype.set = function (x, y, z, w) {
  4450. return this.copyFromFloats(x, y, z, w);
  4451. };
  4452. /**
  4453. * Adds two quaternions
  4454. * @param other defines the second operand
  4455. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4456. */
  4457. Quaternion.prototype.add = function (other) {
  4458. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4459. };
  4460. /**
  4461. * Add a quaternion to the current one
  4462. * @param other defines the quaternion to add
  4463. * @returns the current quaternion
  4464. */
  4465. Quaternion.prototype.addInPlace = function (other) {
  4466. this.x += other.x;
  4467. this.y += other.y;
  4468. this.z += other.z;
  4469. this.w += other.w;
  4470. return this;
  4471. };
  4472. /**
  4473. * Subtract two quaternions
  4474. * @param other defines the second operand
  4475. * @returns a new quaternion as the subtraction result of the given one from the current one
  4476. */
  4477. Quaternion.prototype.subtract = function (other) {
  4478. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4479. };
  4480. /**
  4481. * Multiplies the current quaternion by a scale factor
  4482. * @param value defines the scale factor
  4483. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4484. */
  4485. Quaternion.prototype.scale = function (value) {
  4486. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4487. };
  4488. /**
  4489. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4490. * @param scale defines the scale factor
  4491. * @param result defines the Quaternion object where to store the result
  4492. * @returns the unmodified current quaternion
  4493. */
  4494. Quaternion.prototype.scaleToRef = function (scale, result) {
  4495. result.x = this.x * scale;
  4496. result.y = this.y * scale;
  4497. result.z = this.z * scale;
  4498. result.w = this.w * scale;
  4499. return this;
  4500. };
  4501. /**
  4502. * Multiplies in place the current quaternion by a scale factor
  4503. * @param value defines the scale factor
  4504. * @returns the current modified quaternion
  4505. */
  4506. Quaternion.prototype.scaleInPlace = function (value) {
  4507. this.x *= value;
  4508. this.y *= value;
  4509. this.z *= value;
  4510. this.w *= value;
  4511. return this;
  4512. };
  4513. /**
  4514. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4515. * @param scale defines the scale factor
  4516. * @param result defines the Quaternion object where to store the result
  4517. * @returns the unmodified current quaternion
  4518. */
  4519. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4520. result.x += this.x * scale;
  4521. result.y += this.y * scale;
  4522. result.z += this.z * scale;
  4523. result.w += this.w * scale;
  4524. return this;
  4525. };
  4526. /**
  4527. * Multiplies two quaternions
  4528. * @param q1 defines the second operand
  4529. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4530. */
  4531. Quaternion.prototype.multiply = function (q1) {
  4532. var result = new Quaternion(0, 0, 0, 1.0);
  4533. this.multiplyToRef(q1, result);
  4534. return result;
  4535. };
  4536. /**
  4537. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4538. * @param q1 defines the second operand
  4539. * @param result defines the target quaternion
  4540. * @returns the current quaternion
  4541. */
  4542. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4543. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4544. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4545. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4546. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4547. result.copyFromFloats(x, y, z, w);
  4548. return this;
  4549. };
  4550. /**
  4551. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @returns the currentupdated quaternion
  4554. */
  4555. Quaternion.prototype.multiplyInPlace = function (q1) {
  4556. this.multiplyToRef(q1, this);
  4557. return this;
  4558. };
  4559. /**
  4560. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4561. * @param ref defines the target quaternion
  4562. * @returns the current quaternion
  4563. */
  4564. Quaternion.prototype.conjugateToRef = function (ref) {
  4565. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4566. return this;
  4567. };
  4568. /**
  4569. * Conjugates in place (1-q) the current quaternion
  4570. * @returns the current updated quaternion
  4571. */
  4572. Quaternion.prototype.conjugateInPlace = function () {
  4573. this.x *= -1;
  4574. this.y *= -1;
  4575. this.z *= -1;
  4576. return this;
  4577. };
  4578. /**
  4579. * Conjugates in place (1-q) the current quaternion
  4580. * @returns a new quaternion
  4581. */
  4582. Quaternion.prototype.conjugate = function () {
  4583. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4584. return result;
  4585. };
  4586. /**
  4587. * Gets length of current quaternion
  4588. * @returns the quaternion length (float)
  4589. */
  4590. Quaternion.prototype.length = function () {
  4591. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4592. };
  4593. /**
  4594. * Normalize in place the current quaternion
  4595. * @returns the current updated quaternion
  4596. */
  4597. Quaternion.prototype.normalize = function () {
  4598. var length = 1.0 / this.length();
  4599. this.x *= length;
  4600. this.y *= length;
  4601. this.z *= length;
  4602. this.w *= length;
  4603. return this;
  4604. };
  4605. /**
  4606. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4607. * @param order is a reserved parameter and is ignore for now
  4608. * @returns a new Vector3 containing the Euler angles
  4609. */
  4610. Quaternion.prototype.toEulerAngles = function (order) {
  4611. if (order === void 0) { order = "YZX"; }
  4612. var result = Vector3.Zero();
  4613. this.toEulerAnglesToRef(result, order);
  4614. return result;
  4615. };
  4616. /**
  4617. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4618. * @param result defines the vector which will be filled with the Euler angles
  4619. * @param order is a reserved parameter and is ignore for now
  4620. * @returns the current unchanged quaternion
  4621. */
  4622. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4623. if (order === void 0) { order = "YZX"; }
  4624. var qz = this.z;
  4625. var qx = this.x;
  4626. var qy = this.y;
  4627. var qw = this.w;
  4628. var sqw = qw * qw;
  4629. var sqz = qz * qz;
  4630. var sqx = qx * qx;
  4631. var sqy = qy * qy;
  4632. var zAxisY = qy * qz - qx * qw;
  4633. var limit = .4999999;
  4634. if (zAxisY < -limit) {
  4635. result.y = 2 * Math.atan2(qy, qw);
  4636. result.x = Math.PI / 2;
  4637. result.z = 0;
  4638. }
  4639. else if (zAxisY > limit) {
  4640. result.y = 2 * Math.atan2(qy, qw);
  4641. result.x = -Math.PI / 2;
  4642. result.z = 0;
  4643. }
  4644. else {
  4645. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4646. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4647. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4648. }
  4649. return this;
  4650. };
  4651. /**
  4652. * Updates the given rotation matrix with the current quaternion values
  4653. * @param result defines the target matrix
  4654. * @returns the current unchanged quaternion
  4655. */
  4656. Quaternion.prototype.toRotationMatrix = function (result) {
  4657. var xx = this.x * this.x;
  4658. var yy = this.y * this.y;
  4659. var zz = this.z * this.z;
  4660. var xy = this.x * this.y;
  4661. var zw = this.z * this.w;
  4662. var zx = this.z * this.x;
  4663. var yw = this.y * this.w;
  4664. var yz = this.y * this.z;
  4665. var xw = this.x * this.w;
  4666. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4667. result.m[1] = 2.0 * (xy + zw);
  4668. result.m[2] = 2.0 * (zx - yw);
  4669. result.m[3] = 0;
  4670. result.m[4] = 2.0 * (xy - zw);
  4671. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4672. result.m[6] = 2.0 * (yz + xw);
  4673. result.m[7] = 0;
  4674. result.m[8] = 2.0 * (zx + yw);
  4675. result.m[9] = 2.0 * (yz - xw);
  4676. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4677. result.m[11] = 0;
  4678. result.m[12] = 0;
  4679. result.m[13] = 0;
  4680. result.m[14] = 0;
  4681. result.m[15] = 1.0;
  4682. result._markAsUpdated();
  4683. return this;
  4684. };
  4685. /**
  4686. * Updates the current quaternion from the given rotation matrix values
  4687. * @param matrix defines the source matrix
  4688. * @returns the current updated quaternion
  4689. */
  4690. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4691. Quaternion.FromRotationMatrixToRef(matrix, this);
  4692. return this;
  4693. };
  4694. // Statics
  4695. /**
  4696. * Creates a new quaternion from a rotation matrix
  4697. * @param matrix defines the source matrix
  4698. * @returns a new quaternion created from the given rotation matrix values
  4699. */
  4700. Quaternion.FromRotationMatrix = function (matrix) {
  4701. var result = new Quaternion();
  4702. Quaternion.FromRotationMatrixToRef(matrix, result);
  4703. return result;
  4704. };
  4705. /**
  4706. * Updates the given quaternion with the given rotation matrix values
  4707. * @param matrix defines the source matrix
  4708. * @param result defines the target quaternion
  4709. */
  4710. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4711. var data = matrix.m;
  4712. var m11 = data[0], m12 = data[4], m13 = data[8];
  4713. var m21 = data[1], m22 = data[5], m23 = data[9];
  4714. var m31 = data[2], m32 = data[6], m33 = data[10];
  4715. var trace = m11 + m22 + m33;
  4716. var s;
  4717. if (trace > 0) {
  4718. s = 0.5 / Math.sqrt(trace + 1.0);
  4719. result.w = 0.25 / s;
  4720. result.x = (m32 - m23) * s;
  4721. result.y = (m13 - m31) * s;
  4722. result.z = (m21 - m12) * s;
  4723. }
  4724. else if (m11 > m22 && m11 > m33) {
  4725. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4726. result.w = (m32 - m23) / s;
  4727. result.x = 0.25 * s;
  4728. result.y = (m12 + m21) / s;
  4729. result.z = (m13 + m31) / s;
  4730. }
  4731. else if (m22 > m33) {
  4732. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4733. result.w = (m13 - m31) / s;
  4734. result.x = (m12 + m21) / s;
  4735. result.y = 0.25 * s;
  4736. result.z = (m23 + m32) / s;
  4737. }
  4738. else {
  4739. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4740. result.w = (m21 - m12) / s;
  4741. result.x = (m13 + m31) / s;
  4742. result.y = (m23 + m32) / s;
  4743. result.z = 0.25 * s;
  4744. }
  4745. };
  4746. /**
  4747. * Creates an empty quaternion
  4748. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4749. */
  4750. Quaternion.Zero = function () {
  4751. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4752. };
  4753. /**
  4754. * Inverse a given quaternion
  4755. * @param q defines the source quaternion
  4756. * @returns a new quaternion as the inverted current quaternion
  4757. */
  4758. Quaternion.Inverse = function (q) {
  4759. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4760. };
  4761. /**
  4762. * Creates an identity quaternion
  4763. * @returns the identity quaternion
  4764. */
  4765. Quaternion.Identity = function () {
  4766. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4767. };
  4768. /**
  4769. * Gets a boolean indicating if the given quaternion is identity
  4770. * @param quaternion defines the quaternion to check
  4771. * @returns true if the quaternion is identity
  4772. */
  4773. Quaternion.IsIdentity = function (quaternion) {
  4774. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4775. };
  4776. /**
  4777. * Creates a quaternion from a rotation around an axis
  4778. * @param axis defines the axis to use
  4779. * @param angle defines the angle to use
  4780. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4781. */
  4782. Quaternion.RotationAxis = function (axis, angle) {
  4783. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4784. };
  4785. /**
  4786. * Creates a rotation around an axis and stores it into the given quaternion
  4787. * @param axis defines the axis to use
  4788. * @param angle defines the angle to use
  4789. * @param result defines the target quaternion
  4790. * @returns the target quaternion
  4791. */
  4792. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4793. var sin = Math.sin(angle / 2);
  4794. axis.normalize();
  4795. result.w = Math.cos(angle / 2);
  4796. result.x = axis.x * sin;
  4797. result.y = axis.y * sin;
  4798. result.z = axis.z * sin;
  4799. return result;
  4800. };
  4801. /**
  4802. * Creates a new quaternion from data stored into an array
  4803. * @param array defines the data source
  4804. * @param offset defines the offset in the source array where the data starts
  4805. * @returns a new quaternion
  4806. */
  4807. Quaternion.FromArray = function (array, offset) {
  4808. if (!offset) {
  4809. offset = 0;
  4810. }
  4811. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4812. };
  4813. /**
  4814. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4815. * @param yaw defines the rotation around Y axis
  4816. * @param pitch defines the rotation around X axis
  4817. * @param roll defines the rotation around Z axis
  4818. * @returns the new quaternion
  4819. */
  4820. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4821. var q = new Quaternion();
  4822. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4823. return q;
  4824. };
  4825. /**
  4826. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4827. * @param yaw defines the rotation around Y axis
  4828. * @param pitch defines the rotation around X axis
  4829. * @param roll defines the rotation around Z axis
  4830. * @param result defines the target quaternion
  4831. */
  4832. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4833. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4834. var halfRoll = roll * 0.5;
  4835. var halfPitch = pitch * 0.5;
  4836. var halfYaw = yaw * 0.5;
  4837. var sinRoll = Math.sin(halfRoll);
  4838. var cosRoll = Math.cos(halfRoll);
  4839. var sinPitch = Math.sin(halfPitch);
  4840. var cosPitch = Math.cos(halfPitch);
  4841. var sinYaw = Math.sin(halfYaw);
  4842. var cosYaw = Math.cos(halfYaw);
  4843. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4844. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4845. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4846. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4847. };
  4848. /**
  4849. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4850. * @param alpha defines the rotation around first axis
  4851. * @param beta defines the rotation around second axis
  4852. * @param gamma defines the rotation around third axis
  4853. * @returns the new quaternion
  4854. */
  4855. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4856. var result = new Quaternion();
  4857. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4858. return result;
  4859. };
  4860. /**
  4861. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4862. * @param alpha defines the rotation around first axis
  4863. * @param beta defines the rotation around second axis
  4864. * @param gamma defines the rotation around third axis
  4865. * @param result defines the target quaternion
  4866. */
  4867. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4868. // Produces a quaternion from Euler angles in the z-x-z orientation
  4869. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4870. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4871. var halfBeta = beta * 0.5;
  4872. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4873. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4874. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4875. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4876. };
  4877. /**
  4878. * 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)
  4879. * @param axis1 defines the first axis
  4880. * @param axis2 defines the second axis
  4881. * @param axis3 defines the third axis
  4882. * @returns the new quaternion
  4883. */
  4884. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4885. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4886. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4887. return quat;
  4888. };
  4889. /**
  4890. * 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
  4891. * @param axis1 defines the first axis
  4892. * @param axis2 defines the second axis
  4893. * @param axis3 defines the third axis
  4894. * @param ref defines the target quaternion
  4895. */
  4896. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4897. var rotMat = MathTmp.Matrix[0];
  4898. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4899. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4900. };
  4901. /**
  4902. * Interpolates between two quaternions
  4903. * @param left defines first quaternion
  4904. * @param right defines second quaternion
  4905. * @param amount defines the gradient to use
  4906. * @returns the new interpolated quaternion
  4907. */
  4908. Quaternion.Slerp = function (left, right, amount) {
  4909. var result = Quaternion.Identity();
  4910. Quaternion.SlerpToRef(left, right, amount, result);
  4911. return result;
  4912. };
  4913. /**
  4914. * Interpolates between two quaternions and stores it into a target quaternion
  4915. * @param left defines first quaternion
  4916. * @param right defines second quaternion
  4917. * @param amount defines the gradient to use
  4918. * @param result defines the target quaternion
  4919. */
  4920. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4921. var num2;
  4922. var num3;
  4923. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4924. var flag = false;
  4925. if (num4 < 0) {
  4926. flag = true;
  4927. num4 = -num4;
  4928. }
  4929. if (num4 > 0.999999) {
  4930. num3 = 1 - amount;
  4931. num2 = flag ? -amount : amount;
  4932. }
  4933. else {
  4934. var num5 = Math.acos(num4);
  4935. var num6 = (1.0 / Math.sin(num5));
  4936. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4937. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4938. }
  4939. result.x = (num3 * left.x) + (num2 * right.x);
  4940. result.y = (num3 * left.y) + (num2 * right.y);
  4941. result.z = (num3 * left.z) + (num2 * right.z);
  4942. result.w = (num3 * left.w) + (num2 * right.w);
  4943. };
  4944. /**
  4945. * Interpolate between two quaternions using Hermite interpolation
  4946. * @param value1 defines first quaternion
  4947. * @param tangent1 defines the incoming tangent
  4948. * @param value2 defines second quaternion
  4949. * @param tangent2 defines the outgoing tangent
  4950. * @param amount defines the target quaternion
  4951. * @returns the new interpolated quaternion
  4952. */
  4953. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4954. var squared = amount * amount;
  4955. var cubed = amount * squared;
  4956. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4957. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4958. var part3 = (cubed - (2.0 * squared)) + amount;
  4959. var part4 = cubed - squared;
  4960. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4961. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4962. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4963. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4964. return new Quaternion(x, y, z, w);
  4965. };
  4966. return Quaternion;
  4967. }());
  4968. BABYLON.Quaternion = Quaternion;
  4969. /**
  4970. * Class used to store matrix data (4x4)
  4971. */
  4972. var Matrix = /** @class */ (function () {
  4973. /**
  4974. * Creates an empty matrix (filled with zeros)
  4975. */
  4976. function Matrix() {
  4977. this._isIdentity = false;
  4978. this._isIdentityDirty = true;
  4979. /**
  4980. * Gets or sets the internal data of the matrix
  4981. */
  4982. this.m = new Float32Array(16);
  4983. this._markAsUpdated();
  4984. }
  4985. /** @ignore */
  4986. Matrix.prototype._markAsUpdated = function () {
  4987. this.updateFlag = Matrix._updateFlagSeed++;
  4988. this._isIdentityDirty = true;
  4989. };
  4990. // Properties
  4991. /**
  4992. * Check if the current matrix is indentity
  4993. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4994. * @returns true is the matrix is the identity matrix
  4995. */
  4996. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4997. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4998. if (this._isIdentityDirty) {
  4999. this._isIdentityDirty = false;
  5000. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5001. this._isIdentity = false;
  5002. }
  5003. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5004. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5005. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5006. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5007. this._isIdentity = false;
  5008. }
  5009. else {
  5010. this._isIdentity = true;
  5011. }
  5012. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5013. this._isIdentity = false;
  5014. }
  5015. }
  5016. return this._isIdentity;
  5017. };
  5018. /**
  5019. * Gets the determinant of the matrix
  5020. * @returns the matrix determinant
  5021. */
  5022. Matrix.prototype.determinant = function () {
  5023. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5024. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5025. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5026. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5027. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5028. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5029. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5030. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5031. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5032. };
  5033. // Methods
  5034. /**
  5035. * Returns the matrix as a Float32Array
  5036. * @returns the matrix underlying array
  5037. */
  5038. Matrix.prototype.toArray = function () {
  5039. return this.m;
  5040. };
  5041. /**
  5042. * Returns the matrix as a Float32Array
  5043. * @returns the matrix underlying array.
  5044. */
  5045. Matrix.prototype.asArray = function () {
  5046. return this.toArray();
  5047. };
  5048. /**
  5049. * Inverts the current matrix in place
  5050. * @returns the current inverted matrix
  5051. */
  5052. Matrix.prototype.invert = function () {
  5053. this.invertToRef(this);
  5054. return this;
  5055. };
  5056. /**
  5057. * Sets all the matrix elements to zero
  5058. * @returns the current matrix
  5059. */
  5060. Matrix.prototype.reset = function () {
  5061. for (var index = 0; index < 16; index++) {
  5062. this.m[index] = 0.0;
  5063. }
  5064. this._markAsUpdated();
  5065. return this;
  5066. };
  5067. /**
  5068. * Adds the current matrix with a second one
  5069. * @param other defines the matrix to add
  5070. * @returns a new matrix as the addition of the current matrix and the given one
  5071. */
  5072. Matrix.prototype.add = function (other) {
  5073. var result = new Matrix();
  5074. this.addToRef(other, result);
  5075. return result;
  5076. };
  5077. /**
  5078. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5079. * @param other defines the matrix to add
  5080. * @param result defines the target matrix
  5081. * @returns the current matrix
  5082. */
  5083. Matrix.prototype.addToRef = function (other, result) {
  5084. for (var index = 0; index < 16; index++) {
  5085. result.m[index] = this.m[index] + other.m[index];
  5086. }
  5087. result._markAsUpdated();
  5088. return this;
  5089. };
  5090. /**
  5091. * Adds in place the given matrix to the current matrix
  5092. * @param other defines the second operand
  5093. * @returns the current updated matrix
  5094. */
  5095. Matrix.prototype.addToSelf = function (other) {
  5096. for (var index = 0; index < 16; index++) {
  5097. this.m[index] += other.m[index];
  5098. }
  5099. this._markAsUpdated();
  5100. return this;
  5101. };
  5102. /**
  5103. * Sets the given matrix to the current inverted Matrix
  5104. * @param other defines the target matrix
  5105. * @returns the unmodified current matrix
  5106. */
  5107. Matrix.prototype.invertToRef = function (other) {
  5108. var l1 = this.m[0];
  5109. var l2 = this.m[1];
  5110. var l3 = this.m[2];
  5111. var l4 = this.m[3];
  5112. var l5 = this.m[4];
  5113. var l6 = this.m[5];
  5114. var l7 = this.m[6];
  5115. var l8 = this.m[7];
  5116. var l9 = this.m[8];
  5117. var l10 = this.m[9];
  5118. var l11 = this.m[10];
  5119. var l12 = this.m[11];
  5120. var l13 = this.m[12];
  5121. var l14 = this.m[13];
  5122. var l15 = this.m[14];
  5123. var l16 = this.m[15];
  5124. var l17 = (l11 * l16) - (l12 * l15);
  5125. var l18 = (l10 * l16) - (l12 * l14);
  5126. var l19 = (l10 * l15) - (l11 * l14);
  5127. var l20 = (l9 * l16) - (l12 * l13);
  5128. var l21 = (l9 * l15) - (l11 * l13);
  5129. var l22 = (l9 * l14) - (l10 * l13);
  5130. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5131. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5132. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5133. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5134. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5135. var l28 = (l7 * l16) - (l8 * l15);
  5136. var l29 = (l6 * l16) - (l8 * l14);
  5137. var l30 = (l6 * l15) - (l7 * l14);
  5138. var l31 = (l5 * l16) - (l8 * l13);
  5139. var l32 = (l5 * l15) - (l7 * l13);
  5140. var l33 = (l5 * l14) - (l6 * l13);
  5141. var l34 = (l7 * l12) - (l8 * l11);
  5142. var l35 = (l6 * l12) - (l8 * l10);
  5143. var l36 = (l6 * l11) - (l7 * l10);
  5144. var l37 = (l5 * l12) - (l8 * l9);
  5145. var l38 = (l5 * l11) - (l7 * l9);
  5146. var l39 = (l5 * l10) - (l6 * l9);
  5147. other.m[0] = l23 * l27;
  5148. other.m[4] = l24 * l27;
  5149. other.m[8] = l25 * l27;
  5150. other.m[12] = l26 * l27;
  5151. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5152. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5153. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5154. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5155. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5156. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5157. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5158. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5159. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5160. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5161. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5162. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5163. other._markAsUpdated();
  5164. return this;
  5165. };
  5166. /**
  5167. * Inserts the translation vector (using 3 floats) in the current matrix
  5168. * @param x defines the 1st component of the translation
  5169. * @param y defines the 2nd component of the translation
  5170. * @param z defines the 3rd component of the translation
  5171. * @returns the current updated matrix
  5172. */
  5173. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5174. this.m[12] = x;
  5175. this.m[13] = y;
  5176. this.m[14] = z;
  5177. this._markAsUpdated();
  5178. return this;
  5179. };
  5180. /**
  5181. * Inserts the translation vector in the current matrix
  5182. * @param vector3 defines the translation to insert
  5183. * @returns the current updated matrix
  5184. */
  5185. Matrix.prototype.setTranslation = function (vector3) {
  5186. this.m[12] = vector3.x;
  5187. this.m[13] = vector3.y;
  5188. this.m[14] = vector3.z;
  5189. this._markAsUpdated();
  5190. return this;
  5191. };
  5192. /**
  5193. * Gets the translation value of the current matrix
  5194. * @returns a new Vector3 as the extracted translation from the matrix
  5195. */
  5196. Matrix.prototype.getTranslation = function () {
  5197. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5198. };
  5199. /**
  5200. * Fill a Vector3 with the extracted translation from the matrix
  5201. * @param result defines the Vector3 where to store the translation
  5202. * @returns the current matrix
  5203. */
  5204. Matrix.prototype.getTranslationToRef = function (result) {
  5205. result.x = this.m[12];
  5206. result.y = this.m[13];
  5207. result.z = this.m[14];
  5208. return this;
  5209. };
  5210. /**
  5211. * Remove rotation and scaling part from the matrix
  5212. * @returns the updated matrix
  5213. */
  5214. Matrix.prototype.removeRotationAndScaling = function () {
  5215. this.setRowFromFloats(0, 1, 0, 0, 0);
  5216. this.setRowFromFloats(1, 0, 1, 0, 0);
  5217. this.setRowFromFloats(2, 0, 0, 1, 0);
  5218. return this;
  5219. };
  5220. /**
  5221. * Multiply two matrices
  5222. * @param other defines the second operand
  5223. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5224. */
  5225. Matrix.prototype.multiply = function (other) {
  5226. var result = new Matrix();
  5227. this.multiplyToRef(other, result);
  5228. return result;
  5229. };
  5230. /**
  5231. * Copy the current matrix from the given one
  5232. * @param other defines the source matrix
  5233. * @returns the current updated matrix
  5234. */
  5235. Matrix.prototype.copyFrom = function (other) {
  5236. for (var index = 0; index < 16; index++) {
  5237. this.m[index] = other.m[index];
  5238. }
  5239. this._markAsUpdated();
  5240. return this;
  5241. };
  5242. /**
  5243. * Populates the given array from the starting index with the current matrix values
  5244. * @param array defines the target array
  5245. * @param offset defines the offset in the target array where to start storing values
  5246. * @returns the current matrix
  5247. */
  5248. Matrix.prototype.copyToArray = function (array, offset) {
  5249. if (offset === void 0) { offset = 0; }
  5250. for (var index = 0; index < 16; index++) {
  5251. array[offset + index] = this.m[index];
  5252. }
  5253. return this;
  5254. };
  5255. /**
  5256. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5257. * @param other defines the second operand
  5258. * @param result defines the matrix where to store the multiplication
  5259. * @returns the current matrix
  5260. */
  5261. Matrix.prototype.multiplyToRef = function (other, result) {
  5262. this.multiplyToArray(other, result.m, 0);
  5263. result._markAsUpdated();
  5264. return this;
  5265. };
  5266. /**
  5267. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5268. * @param other defines the second operand
  5269. * @param result defines the array where to store the multiplication
  5270. * @param offset defines the offset in the target array where to start storing values
  5271. * @returns the current matrix
  5272. */
  5273. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5274. var tm0 = this.m[0];
  5275. var tm1 = this.m[1];
  5276. var tm2 = this.m[2];
  5277. var tm3 = this.m[3];
  5278. var tm4 = this.m[4];
  5279. var tm5 = this.m[5];
  5280. var tm6 = this.m[6];
  5281. var tm7 = this.m[7];
  5282. var tm8 = this.m[8];
  5283. var tm9 = this.m[9];
  5284. var tm10 = this.m[10];
  5285. var tm11 = this.m[11];
  5286. var tm12 = this.m[12];
  5287. var tm13 = this.m[13];
  5288. var tm14 = this.m[14];
  5289. var tm15 = this.m[15];
  5290. var om0 = other.m[0];
  5291. var om1 = other.m[1];
  5292. var om2 = other.m[2];
  5293. var om3 = other.m[3];
  5294. var om4 = other.m[4];
  5295. var om5 = other.m[5];
  5296. var om6 = other.m[6];
  5297. var om7 = other.m[7];
  5298. var om8 = other.m[8];
  5299. var om9 = other.m[9];
  5300. var om10 = other.m[10];
  5301. var om11 = other.m[11];
  5302. var om12 = other.m[12];
  5303. var om13 = other.m[13];
  5304. var om14 = other.m[14];
  5305. var om15 = other.m[15];
  5306. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5307. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5308. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5309. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5310. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5311. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5312. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5313. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5314. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5315. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5316. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5317. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5318. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5319. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5320. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5321. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5322. return this;
  5323. };
  5324. /**
  5325. * Check equality between this matrix and a second one
  5326. * @param value defines the second matrix to compare
  5327. * @returns true is the current matrix and the given one values are strictly equal
  5328. */
  5329. Matrix.prototype.equals = function (value) {
  5330. return value &&
  5331. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5332. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5333. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5334. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5335. };
  5336. /**
  5337. * Clone the current matrix
  5338. * @returns a new matrix from the current matrix
  5339. */
  5340. Matrix.prototype.clone = function () {
  5341. 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]);
  5342. };
  5343. /**
  5344. * Returns the name of the current matrix class
  5345. * @returns the string "Matrix"
  5346. */
  5347. Matrix.prototype.getClassName = function () {
  5348. return "Matrix";
  5349. };
  5350. /**
  5351. * Gets the hash code of the current matrix
  5352. * @returns the hash code
  5353. */
  5354. Matrix.prototype.getHashCode = function () {
  5355. var hash = this.m[0] || 0;
  5356. for (var i = 1; i < 16; i++) {
  5357. hash = (hash * 397) ^ (this.m[i] || 0);
  5358. }
  5359. return hash;
  5360. };
  5361. /**
  5362. * Decomposes the current Matrix into a translation, rotation and scaling components
  5363. * @param scale defines the scale vector3 given as a reference to update
  5364. * @param rotation defines the rotation quaternion given as a reference to update
  5365. * @param translation defines the translation vector3 given as a reference to update
  5366. * @returns true if operation was successful
  5367. */
  5368. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5369. if (translation) {
  5370. translation.x = this.m[12];
  5371. translation.y = this.m[13];
  5372. translation.z = this.m[14];
  5373. }
  5374. scale = scale || MathTmp.Vector3[0];
  5375. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5376. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5377. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5378. if (this.determinant() <= 0) {
  5379. scale.y *= -1;
  5380. }
  5381. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5382. if (rotation) {
  5383. rotation.x = 0;
  5384. rotation.y = 0;
  5385. rotation.z = 0;
  5386. rotation.w = 1;
  5387. }
  5388. return false;
  5389. }
  5390. if (rotation) {
  5391. 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]);
  5392. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5393. }
  5394. return true;
  5395. };
  5396. /**
  5397. * Gets specific row of the matrix
  5398. * @param index defines the number of the row to get
  5399. * @returns the index-th row of the current matrix as a new Vector4
  5400. */
  5401. Matrix.prototype.getRow = function (index) {
  5402. if (index < 0 || index > 3) {
  5403. return null;
  5404. }
  5405. var i = index * 4;
  5406. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5407. };
  5408. /**
  5409. * Sets the index-th row of the current matrix to the vector4 values
  5410. * @param index defines the number of the row to set
  5411. * @param row defines the target vector4
  5412. * @returns the updated current matrix
  5413. */
  5414. Matrix.prototype.setRow = function (index, row) {
  5415. if (index < 0 || index > 3) {
  5416. return this;
  5417. }
  5418. var i = index * 4;
  5419. this.m[i + 0] = row.x;
  5420. this.m[i + 1] = row.y;
  5421. this.m[i + 2] = row.z;
  5422. this.m[i + 3] = row.w;
  5423. this._markAsUpdated();
  5424. return this;
  5425. };
  5426. /**
  5427. * Compute the transpose of the matrix
  5428. * @returns the new transposed matrix
  5429. */
  5430. Matrix.prototype.transpose = function () {
  5431. return Matrix.Transpose(this);
  5432. };
  5433. /**
  5434. * Compute the transpose of the matrix and store it in a given matrix
  5435. * @param result defines the target matrix
  5436. * @returns the current matrix
  5437. */
  5438. Matrix.prototype.transposeToRef = function (result) {
  5439. Matrix.TransposeToRef(this, result);
  5440. return this;
  5441. };
  5442. /**
  5443. * Sets the index-th row of the current matrix with the given 4 x float values
  5444. * @param index defines the row index
  5445. * @param x defines the x component to set
  5446. * @param y defines the y component to set
  5447. * @param z defines the z component to set
  5448. * @param w defines the w component to set
  5449. * @returns the updated current matrix
  5450. */
  5451. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5452. if (index < 0 || index > 3) {
  5453. return this;
  5454. }
  5455. var i = index * 4;
  5456. this.m[i + 0] = x;
  5457. this.m[i + 1] = y;
  5458. this.m[i + 2] = z;
  5459. this.m[i + 3] = w;
  5460. this._markAsUpdated();
  5461. return this;
  5462. };
  5463. /**
  5464. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5465. * @param scale defines the scale factor
  5466. * @returns a new matrix
  5467. */
  5468. Matrix.prototype.scale = function (scale) {
  5469. var result = new Matrix();
  5470. this.scaleToRef(scale, result);
  5471. return result;
  5472. };
  5473. /**
  5474. * Scale the current matrix values by a factor to a given result matrix
  5475. * @param scale defines the scale factor
  5476. * @param result defines the matrix to store the result
  5477. * @returns the current matrix
  5478. */
  5479. Matrix.prototype.scaleToRef = function (scale, result) {
  5480. for (var index = 0; index < 16; index++) {
  5481. result.m[index] = this.m[index] * scale;
  5482. }
  5483. result._markAsUpdated();
  5484. return this;
  5485. };
  5486. /**
  5487. * Scale the current matrix values by a factor and add the result to a given matrix
  5488. * @param scale defines the scale factor
  5489. * @param result defines the Matrix to store the result
  5490. * @returns the current matrix
  5491. */
  5492. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5493. for (var index = 0; index < 16; index++) {
  5494. result.m[index] += this.m[index] * scale;
  5495. }
  5496. result._markAsUpdated();
  5497. return this;
  5498. };
  5499. /**
  5500. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5501. * @param ref matrix to store the result
  5502. */
  5503. Matrix.prototype.toNormalMatrix = function (ref) {
  5504. this.invertToRef(ref);
  5505. ref.transpose();
  5506. var m = ref.m;
  5507. 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);
  5508. };
  5509. /**
  5510. * Gets only rotation part of the current matrix
  5511. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5512. */
  5513. Matrix.prototype.getRotationMatrix = function () {
  5514. var result = Matrix.Identity();
  5515. this.getRotationMatrixToRef(result);
  5516. return result;
  5517. };
  5518. /**
  5519. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5520. * @param result defines the target matrix to store data to
  5521. * @returns the current matrix
  5522. */
  5523. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5524. var m = this.m;
  5525. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5526. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5527. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5528. if (this.determinant() <= 0) {
  5529. sy *= -1;
  5530. }
  5531. if (sx === 0 || sy === 0 || sz === 0) {
  5532. Matrix.IdentityToRef(result);
  5533. }
  5534. else {
  5535. 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);
  5536. }
  5537. return this;
  5538. };
  5539. // Statics
  5540. /**
  5541. * Creates a matrix from an array
  5542. * @param array defines the source array
  5543. * @param offset defines an offset in the source array
  5544. * @returns a new Matrix set from the starting index of the given array
  5545. */
  5546. Matrix.FromArray = function (array, offset) {
  5547. var result = new Matrix();
  5548. if (!offset) {
  5549. offset = 0;
  5550. }
  5551. Matrix.FromArrayToRef(array, offset, result);
  5552. return result;
  5553. };
  5554. /**
  5555. * Copy the content of an array into a given matrix
  5556. * @param array defines the source array
  5557. * @param offset defines an offset in the source array
  5558. * @param result defines the target matrix
  5559. */
  5560. Matrix.FromArrayToRef = function (array, offset, result) {
  5561. for (var index = 0; index < 16; index++) {
  5562. result.m[index] = array[index + offset];
  5563. }
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Stores an array into a matrix after having multiplied each component by a given factor
  5568. * @param array defines the source array
  5569. * @param offset defines the offset in the source array
  5570. * @param scale defines the scaling factor
  5571. * @param result defines the target matrix
  5572. */
  5573. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5574. for (var index = 0; index < 16; index++) {
  5575. result.m[index] = array[index + offset] * scale;
  5576. }
  5577. result._markAsUpdated();
  5578. };
  5579. /**
  5580. * Stores a list of values (16) inside a given matrix
  5581. * @param initialM11 defines 1st value of 1st row
  5582. * @param initialM12 defines 2nd value of 1st row
  5583. * @param initialM13 defines 3rd value of 1st row
  5584. * @param initialM14 defines 4th value of 1st row
  5585. * @param initialM21 defines 1st value of 2nd row
  5586. * @param initialM22 defines 2nd value of 2nd row
  5587. * @param initialM23 defines 3rd value of 2nd row
  5588. * @param initialM24 defines 4th value of 2nd row
  5589. * @param initialM31 defines 1st value of 3rd row
  5590. * @param initialM32 defines 2nd value of 3rd row
  5591. * @param initialM33 defines 3rd value of 3rd row
  5592. * @param initialM34 defines 4th value of 3rd row
  5593. * @param initialM41 defines 1st value of 4th row
  5594. * @param initialM42 defines 2nd value of 4th row
  5595. * @param initialM43 defines 3rd value of 4th row
  5596. * @param initialM44 defines 4th value of 4th row
  5597. * @param result defines the target matrix
  5598. */
  5599. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5600. result.m[0] = initialM11;
  5601. result.m[1] = initialM12;
  5602. result.m[2] = initialM13;
  5603. result.m[3] = initialM14;
  5604. result.m[4] = initialM21;
  5605. result.m[5] = initialM22;
  5606. result.m[6] = initialM23;
  5607. result.m[7] = initialM24;
  5608. result.m[8] = initialM31;
  5609. result.m[9] = initialM32;
  5610. result.m[10] = initialM33;
  5611. result.m[11] = initialM34;
  5612. result.m[12] = initialM41;
  5613. result.m[13] = initialM42;
  5614. result.m[14] = initialM43;
  5615. result.m[15] = initialM44;
  5616. result._markAsUpdated();
  5617. };
  5618. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5619. /**
  5620. * Gets an identity matrix that must not be updated
  5621. */
  5622. get: function () {
  5623. return Matrix._identityReadOnly;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. /**
  5629. * Creates new matrix from a list of values (16)
  5630. * @param initialM11 defines 1st value of 1st row
  5631. * @param initialM12 defines 2nd value of 1st row
  5632. * @param initialM13 defines 3rd value of 1st row
  5633. * @param initialM14 defines 4th value of 1st row
  5634. * @param initialM21 defines 1st value of 2nd row
  5635. * @param initialM22 defines 2nd value of 2nd row
  5636. * @param initialM23 defines 3rd value of 2nd row
  5637. * @param initialM24 defines 4th value of 2nd row
  5638. * @param initialM31 defines 1st value of 3rd row
  5639. * @param initialM32 defines 2nd value of 3rd row
  5640. * @param initialM33 defines 3rd value of 3rd row
  5641. * @param initialM34 defines 4th value of 3rd row
  5642. * @param initialM41 defines 1st value of 4th row
  5643. * @param initialM42 defines 2nd value of 4th row
  5644. * @param initialM43 defines 3rd value of 4th row
  5645. * @param initialM44 defines 4th value of 4th row
  5646. * @returns the new matrix
  5647. */
  5648. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5649. var result = new Matrix();
  5650. result.m[0] = initialM11;
  5651. result.m[1] = initialM12;
  5652. result.m[2] = initialM13;
  5653. result.m[3] = initialM14;
  5654. result.m[4] = initialM21;
  5655. result.m[5] = initialM22;
  5656. result.m[6] = initialM23;
  5657. result.m[7] = initialM24;
  5658. result.m[8] = initialM31;
  5659. result.m[9] = initialM32;
  5660. result.m[10] = initialM33;
  5661. result.m[11] = initialM34;
  5662. result.m[12] = initialM41;
  5663. result.m[13] = initialM42;
  5664. result.m[14] = initialM43;
  5665. result.m[15] = initialM44;
  5666. return result;
  5667. };
  5668. /**
  5669. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5670. * @param scale defines the scale vector3
  5671. * @param rotation defines the rotation quaternion
  5672. * @param translation defines the translation vector3
  5673. * @returns a new matrix
  5674. */
  5675. Matrix.Compose = function (scale, rotation, translation) {
  5676. var result = Matrix.Identity();
  5677. Matrix.ComposeToRef(scale, rotation, translation, result);
  5678. return result;
  5679. };
  5680. /**
  5681. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5682. * @param scale defines the scale vector3
  5683. * @param rotation defines the rotation quaternion
  5684. * @param translation defines the translation vector3
  5685. * @param result defines the target matrix
  5686. */
  5687. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5688. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5689. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5690. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5691. result.setTranslation(translation);
  5692. };
  5693. /**
  5694. * Creates a new identity matrix
  5695. * @returns a new identity matrix
  5696. */
  5697. Matrix.Identity = function () {
  5698. 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);
  5699. };
  5700. /**
  5701. * Creates a new identity matrix and stores the result in a given matrix
  5702. * @param result defines the target matrix
  5703. */
  5704. Matrix.IdentityToRef = function (result) {
  5705. 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);
  5706. };
  5707. /**
  5708. * Creates a new zero matrix
  5709. * @returns a new zero matrix
  5710. */
  5711. Matrix.Zero = function () {
  5712. 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);
  5713. };
  5714. /**
  5715. * Creates a new rotation matrix for "angle" radians around the X axis
  5716. * @param angle defines the angle (in radians) to use
  5717. * @return the new matrix
  5718. */
  5719. Matrix.RotationX = function (angle) {
  5720. var result = new Matrix();
  5721. Matrix.RotationXToRef(angle, result);
  5722. return result;
  5723. };
  5724. /**
  5725. * Creates a new matrix as the invert of a given matrix
  5726. * @param source defines the source matrix
  5727. * @returns the new matrix
  5728. */
  5729. Matrix.Invert = function (source) {
  5730. var result = new Matrix();
  5731. source.invertToRef(result);
  5732. return result;
  5733. };
  5734. /**
  5735. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5736. * @param angle defines the angle (in radians) to use
  5737. * @param result defines the target matrix
  5738. */
  5739. Matrix.RotationXToRef = function (angle, result) {
  5740. var s = Math.sin(angle);
  5741. var c = Math.cos(angle);
  5742. result.m[0] = 1.0;
  5743. result.m[15] = 1.0;
  5744. result.m[5] = c;
  5745. result.m[10] = c;
  5746. result.m[9] = -s;
  5747. result.m[6] = s;
  5748. result.m[1] = 0.0;
  5749. result.m[2] = 0.0;
  5750. result.m[3] = 0.0;
  5751. result.m[4] = 0.0;
  5752. result.m[7] = 0.0;
  5753. result.m[8] = 0.0;
  5754. result.m[11] = 0.0;
  5755. result.m[12] = 0.0;
  5756. result.m[13] = 0.0;
  5757. result.m[14] = 0.0;
  5758. result._markAsUpdated();
  5759. };
  5760. /**
  5761. * Creates a new rotation matrix for "angle" radians around the Y axis
  5762. * @param angle defines the angle (in radians) to use
  5763. * @return the new matrix
  5764. */
  5765. Matrix.RotationY = function (angle) {
  5766. var result = new Matrix();
  5767. Matrix.RotationYToRef(angle, result);
  5768. return result;
  5769. };
  5770. /**
  5771. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5772. * @param angle defines the angle (in radians) to use
  5773. * @param result defines the target matrix
  5774. */
  5775. Matrix.RotationYToRef = function (angle, result) {
  5776. var s = Math.sin(angle);
  5777. var c = Math.cos(angle);
  5778. result.m[5] = 1.0;
  5779. result.m[15] = 1.0;
  5780. result.m[0] = c;
  5781. result.m[2] = -s;
  5782. result.m[8] = s;
  5783. result.m[10] = c;
  5784. result.m[1] = 0.0;
  5785. result.m[3] = 0.0;
  5786. result.m[4] = 0.0;
  5787. result.m[6] = 0.0;
  5788. result.m[7] = 0.0;
  5789. result.m[9] = 0.0;
  5790. result.m[11] = 0.0;
  5791. result.m[12] = 0.0;
  5792. result.m[13] = 0.0;
  5793. result.m[14] = 0.0;
  5794. result._markAsUpdated();
  5795. };
  5796. /**
  5797. * Creates a new rotation matrix for "angle" radians around the Z axis
  5798. * @param angle defines the angle (in radians) to use
  5799. * @return the new matrix
  5800. */
  5801. Matrix.RotationZ = function (angle) {
  5802. var result = new Matrix();
  5803. Matrix.RotationZToRef(angle, result);
  5804. return result;
  5805. };
  5806. /**
  5807. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5808. * @param angle defines the angle (in radians) to use
  5809. * @param result defines the target matrix
  5810. */
  5811. Matrix.RotationZToRef = function (angle, result) {
  5812. var s = Math.sin(angle);
  5813. var c = Math.cos(angle);
  5814. result.m[10] = 1.0;
  5815. result.m[15] = 1.0;
  5816. result.m[0] = c;
  5817. result.m[1] = s;
  5818. result.m[4] = -s;
  5819. result.m[5] = c;
  5820. result.m[2] = 0.0;
  5821. result.m[3] = 0.0;
  5822. result.m[6] = 0.0;
  5823. result.m[7] = 0.0;
  5824. result.m[8] = 0.0;
  5825. result.m[9] = 0.0;
  5826. result.m[11] = 0.0;
  5827. result.m[12] = 0.0;
  5828. result.m[13] = 0.0;
  5829. result.m[14] = 0.0;
  5830. result._markAsUpdated();
  5831. };
  5832. /**
  5833. * Creates a new rotation matrix for "angle" radians around the given axis
  5834. * @param axis defines the axis to use
  5835. * @param angle defines the angle (in radians) to use
  5836. * @return the new matrix
  5837. */
  5838. Matrix.RotationAxis = function (axis, angle) {
  5839. var result = Matrix.Zero();
  5840. Matrix.RotationAxisToRef(axis, angle, result);
  5841. return result;
  5842. };
  5843. /**
  5844. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5845. * @param axis defines the axis to use
  5846. * @param angle defines the angle (in radians) to use
  5847. * @param result defines the target matrix
  5848. */
  5849. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5850. var s = Math.sin(-angle);
  5851. var c = Math.cos(-angle);
  5852. var c1 = 1 - c;
  5853. axis.normalize();
  5854. result.m[0] = (axis.x * axis.x) * c1 + c;
  5855. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5856. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5857. result.m[3] = 0.0;
  5858. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5859. result.m[5] = (axis.y * axis.y) * c1 + c;
  5860. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5861. result.m[7] = 0.0;
  5862. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5863. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5864. result.m[10] = (axis.z * axis.z) * c1 + c;
  5865. result.m[11] = 0.0;
  5866. result.m[15] = 1.0;
  5867. result._markAsUpdated();
  5868. };
  5869. /**
  5870. * Creates a rotation matrix
  5871. * @param yaw defines the yaw angle in radians (Y axis)
  5872. * @param pitch defines the pitch angle in radians (X axis)
  5873. * @param roll defines the roll angle in radians (X axis)
  5874. * @returns the new rotation matrix
  5875. */
  5876. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5877. var result = new Matrix();
  5878. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5879. return result;
  5880. };
  5881. /**
  5882. * Creates a rotation matrix and stores it in a given matrix
  5883. * @param yaw defines the yaw angle in radians (Y axis)
  5884. * @param pitch defines the pitch angle in radians (X axis)
  5885. * @param roll defines the roll angle in radians (X axis)
  5886. * @param result defines the target matrix
  5887. */
  5888. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5889. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5890. this._tempQuaternion.toRotationMatrix(result);
  5891. };
  5892. /**
  5893. * Creates a scaling matrix
  5894. * @param x defines the scale factor on X axis
  5895. * @param y defines the scale factor on Y axis
  5896. * @param z defines the scale factor on Z axis
  5897. * @returns the new matrix
  5898. */
  5899. Matrix.Scaling = function (x, y, z) {
  5900. var result = Matrix.Zero();
  5901. Matrix.ScalingToRef(x, y, z, result);
  5902. return result;
  5903. };
  5904. /**
  5905. * Creates a scaling matrix and stores it in a given matrix
  5906. * @param x defines the scale factor on X axis
  5907. * @param y defines the scale factor on Y axis
  5908. * @param z defines the scale factor on Z axis
  5909. * @param result defines the target matrix
  5910. */
  5911. Matrix.ScalingToRef = function (x, y, z, result) {
  5912. result.m[0] = x;
  5913. result.m[1] = 0.0;
  5914. result.m[2] = 0.0;
  5915. result.m[3] = 0.0;
  5916. result.m[4] = 0.0;
  5917. result.m[5] = y;
  5918. result.m[6] = 0.0;
  5919. result.m[7] = 0.0;
  5920. result.m[8] = 0.0;
  5921. result.m[9] = 0.0;
  5922. result.m[10] = z;
  5923. result.m[11] = 0.0;
  5924. result.m[12] = 0.0;
  5925. result.m[13] = 0.0;
  5926. result.m[14] = 0.0;
  5927. result.m[15] = 1.0;
  5928. result._markAsUpdated();
  5929. };
  5930. /**
  5931. * Creates a translation matrix
  5932. * @param x defines the translation on X axis
  5933. * @param y defines the translation on Y axis
  5934. * @param z defines the translationon Z axis
  5935. * @returns the new matrix
  5936. */
  5937. Matrix.Translation = function (x, y, z) {
  5938. var result = Matrix.Identity();
  5939. Matrix.TranslationToRef(x, y, z, result);
  5940. return result;
  5941. };
  5942. /**
  5943. * Creates a translation matrix and stores it in a given matrix
  5944. * @param x defines the translation on X axis
  5945. * @param y defines the translation on Y axis
  5946. * @param z defines the translationon Z axis
  5947. * @param result defines the target matrix
  5948. */
  5949. Matrix.TranslationToRef = function (x, y, z, result) {
  5950. 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);
  5951. };
  5952. /**
  5953. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5954. * @param startValue defines the start value
  5955. * @param endValue defines the end value
  5956. * @param gradient defines the gradient factor
  5957. * @returns the new matrix
  5958. */
  5959. Matrix.Lerp = function (startValue, endValue, gradient) {
  5960. var result = Matrix.Zero();
  5961. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5962. return result;
  5963. };
  5964. /**
  5965. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5966. * @param startValue defines the start value
  5967. * @param endValue defines the end value
  5968. * @param gradient defines the gradient factor
  5969. * @param result defines the Matrix object where to store data
  5970. */
  5971. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5972. for (var index = 0; index < 16; index++) {
  5973. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5974. }
  5975. result._markAsUpdated();
  5976. };
  5977. /**
  5978. * Builds a new matrix whose values are computed by:
  5979. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5980. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5981. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5982. * @param startValue defines the first matrix
  5983. * @param endValue defines the second matrix
  5984. * @param gradient defines the gradient between the two matrices
  5985. * @returns the new matrix
  5986. */
  5987. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5988. var result = Matrix.Zero();
  5989. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5990. return result;
  5991. };
  5992. /**
  5993. * Update a matrix to values which are computed by:
  5994. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5995. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5996. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5997. * @param startValue defines the first matrix
  5998. * @param endValue defines the second matrix
  5999. * @param gradient defines the gradient between the two matrices
  6000. * @param result defines the target matrix
  6001. */
  6002. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6003. var startScale = MathTmp.Vector3[0];
  6004. var startRotation = MathTmp.Quaternion[0];
  6005. var startTranslation = MathTmp.Vector3[1];
  6006. startValue.decompose(startScale, startRotation, startTranslation);
  6007. var endScale = MathTmp.Vector3[2];
  6008. var endRotation = MathTmp.Quaternion[1];
  6009. var endTranslation = MathTmp.Vector3[3];
  6010. endValue.decompose(endScale, endRotation, endTranslation);
  6011. var resultScale = MathTmp.Vector3[4];
  6012. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6013. var resultRotation = MathTmp.Quaternion[2];
  6014. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6015. var resultTranslation = MathTmp.Vector3[5];
  6016. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6017. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6018. };
  6019. /**
  6020. * 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"
  6021. * This function works in left handed mode
  6022. * @param eye defines the final position of the entity
  6023. * @param target defines where the entity should look at
  6024. * @param up defines the up vector for the entity
  6025. * @returns the new matrix
  6026. */
  6027. Matrix.LookAtLH = function (eye, target, up) {
  6028. var result = Matrix.Zero();
  6029. Matrix.LookAtLHToRef(eye, target, up, result);
  6030. return result;
  6031. };
  6032. /**
  6033. * 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".
  6034. * This function works in left handed mode
  6035. * @param eye defines the final position of the entity
  6036. * @param target defines where the entity should look at
  6037. * @param up defines the up vector for the entity
  6038. * @param result defines the target matrix
  6039. */
  6040. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6041. // Z axis
  6042. target.subtractToRef(eye, this._zAxis);
  6043. this._zAxis.normalize();
  6044. // X axis
  6045. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6046. if (this._xAxis.lengthSquared() === 0) {
  6047. this._xAxis.x = 1.0;
  6048. }
  6049. else {
  6050. this._xAxis.normalize();
  6051. }
  6052. // Y axis
  6053. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6054. this._yAxis.normalize();
  6055. // Eye angles
  6056. var ex = -Vector3.Dot(this._xAxis, eye);
  6057. var ey = -Vector3.Dot(this._yAxis, eye);
  6058. var ez = -Vector3.Dot(this._zAxis, eye);
  6059. 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);
  6060. };
  6061. /**
  6062. * 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"
  6063. * This function works in right handed mode
  6064. * @param eye defines the final position of the entity
  6065. * @param target defines where the entity should look at
  6066. * @param up defines the up vector for the entity
  6067. * @returns the new matrix
  6068. */
  6069. Matrix.LookAtRH = function (eye, target, up) {
  6070. var result = Matrix.Zero();
  6071. Matrix.LookAtRHToRef(eye, target, up, result);
  6072. return result;
  6073. };
  6074. /**
  6075. * 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".
  6076. * This function works in right handed mode
  6077. * @param eye defines the final position of the entity
  6078. * @param target defines where the entity should look at
  6079. * @param up defines the up vector for the entity
  6080. * @param result defines the target matrix
  6081. */
  6082. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6083. // Z axis
  6084. eye.subtractToRef(target, this._zAxis);
  6085. this._zAxis.normalize();
  6086. // X axis
  6087. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6088. if (this._xAxis.lengthSquared() === 0) {
  6089. this._xAxis.x = 1.0;
  6090. }
  6091. else {
  6092. this._xAxis.normalize();
  6093. }
  6094. // Y axis
  6095. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6096. this._yAxis.normalize();
  6097. // Eye angles
  6098. var ex = -Vector3.Dot(this._xAxis, eye);
  6099. var ey = -Vector3.Dot(this._yAxis, eye);
  6100. var ez = -Vector3.Dot(this._zAxis, eye);
  6101. 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);
  6102. };
  6103. /**
  6104. * Create a left-handed orthographic projection matrix
  6105. * @param width defines the viewport width
  6106. * @param height defines the viewport height
  6107. * @param znear defines the near clip plane
  6108. * @param zfar defines the far clip plane
  6109. * @returns a new matrix as a left-handed orthographic projection matrix
  6110. */
  6111. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6112. var matrix = Matrix.Zero();
  6113. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6114. return matrix;
  6115. };
  6116. /**
  6117. * Store a left-handed orthographic projection to a given matrix
  6118. * @param width defines the viewport width
  6119. * @param height defines the viewport height
  6120. * @param znear defines the near clip plane
  6121. * @param zfar defines the far clip plane
  6122. * @param result defines the target matrix
  6123. */
  6124. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6125. var n = znear;
  6126. var f = zfar;
  6127. var a = 2.0 / width;
  6128. var b = 2.0 / height;
  6129. var c = 2.0 / (f - n);
  6130. var d = -(f + n) / (f - n);
  6131. 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);
  6132. };
  6133. /**
  6134. * Create a left-handed orthographic projection matrix
  6135. * @param left defines the viewport left coordinate
  6136. * @param right defines the viewport right coordinate
  6137. * @param bottom defines the viewport bottom coordinate
  6138. * @param top defines the viewport top coordinate
  6139. * @param znear defines the near clip plane
  6140. * @param zfar defines the far clip plane
  6141. * @returns a new matrix as a left-handed orthographic projection matrix
  6142. */
  6143. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6144. var matrix = Matrix.Zero();
  6145. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6146. return matrix;
  6147. };
  6148. /**
  6149. * Stores a left-handed orthographic projection into a given matrix
  6150. * @param left defines the viewport left coordinate
  6151. * @param right defines the viewport right coordinate
  6152. * @param bottom defines the viewport bottom coordinate
  6153. * @param top defines the viewport top coordinate
  6154. * @param znear defines the near clip plane
  6155. * @param zfar defines the far clip plane
  6156. * @param result defines the target matrix
  6157. */
  6158. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6159. var n = znear;
  6160. var f = zfar;
  6161. var a = 2.0 / (right - left);
  6162. var b = 2.0 / (top - bottom);
  6163. var c = 2.0 / (f - n);
  6164. var d = -(f + n) / (f - n);
  6165. var i0 = (left + right) / (left - right);
  6166. var i1 = (top + bottom) / (bottom - top);
  6167. 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);
  6168. };
  6169. /**
  6170. * Creates a right-handed orthographic projection matrix
  6171. * @param left defines the viewport left coordinate
  6172. * @param right defines the viewport right coordinate
  6173. * @param bottom defines the viewport bottom coordinate
  6174. * @param top defines the viewport top coordinate
  6175. * @param znear defines the near clip plane
  6176. * @param zfar defines the far clip plane
  6177. * @returns a new matrix as a right-handed orthographic projection matrix
  6178. */
  6179. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6180. var matrix = Matrix.Zero();
  6181. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6182. return matrix;
  6183. };
  6184. /**
  6185. * Stores a right-handed orthographic projection into a given matrix
  6186. * @param left defines the viewport left coordinate
  6187. * @param right defines the viewport right coordinate
  6188. * @param bottom defines the viewport bottom coordinate
  6189. * @param top defines the viewport top coordinate
  6190. * @param znear defines the near clip plane
  6191. * @param zfar defines the far clip plane
  6192. * @param result defines the target matrix
  6193. */
  6194. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6195. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6196. result.m[10] *= -1.0;
  6197. };
  6198. /**
  6199. * Creates a left-handed perspective projection matrix
  6200. * @param width defines the viewport width
  6201. * @param height defines the viewport height
  6202. * @param znear defines the near clip plane
  6203. * @param zfar defines the far clip plane
  6204. * @returns a new matrix as a left-handed perspective projection matrix
  6205. */
  6206. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6207. var matrix = Matrix.Zero();
  6208. var n = znear;
  6209. var f = zfar;
  6210. var a = 2.0 * n / width;
  6211. var b = 2.0 * n / height;
  6212. var c = (f + n) / (f - n);
  6213. var d = -2.0 * f * n / (f - n);
  6214. 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);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Creates a left-handed perspective projection matrix
  6219. * @param fov defines the horizontal field of view
  6220. * @param aspect defines the aspect ratio
  6221. * @param znear defines the near clip plane
  6222. * @param zfar defines the far clip plane
  6223. * @returns a new matrix as a left-handed perspective projection matrix
  6224. */
  6225. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6226. var matrix = Matrix.Zero();
  6227. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6228. return matrix;
  6229. };
  6230. /**
  6231. * Stores a left-handed perspective projection into a given matrix
  6232. * @param fov defines the horizontal field of view
  6233. * @param aspect defines the aspect ratio
  6234. * @param znear defines the near clip plane
  6235. * @param zfar defines the far clip plane
  6236. * @param result defines the target matrix
  6237. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6238. */
  6239. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6240. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6241. var n = znear;
  6242. var f = zfar;
  6243. var t = 1.0 / (Math.tan(fov * 0.5));
  6244. var a = isVerticalFovFixed ? (t / aspect) : t;
  6245. var b = isVerticalFovFixed ? t : (t * aspect);
  6246. var c = (f + n) / (f - n);
  6247. var d = -2.0 * f * n / (f - n);
  6248. 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);
  6249. };
  6250. /**
  6251. * Creates a right-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a right-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a right-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. //alternatively this could be expressed as:
  6274. // m = PerspectiveFovLHToRef
  6275. // m[10] *= -1.0;
  6276. // m[11] *= -1.0;
  6277. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6278. var n = znear;
  6279. var f = zfar;
  6280. var t = 1.0 / (Math.tan(fov * 0.5));
  6281. var a = isVerticalFovFixed ? (t / aspect) : t;
  6282. var b = isVerticalFovFixed ? t : (t * aspect);
  6283. var c = -(f + n) / (f - n);
  6284. var d = -2 * f * n / (f - n);
  6285. 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);
  6286. };
  6287. /**
  6288. * Stores a perspective projection for WebVR info a given matrix
  6289. * @param fov defines the field of view
  6290. * @param znear defines the near clip plane
  6291. * @param zfar defines the far clip plane
  6292. * @param result defines the target matrix
  6293. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6294. */
  6295. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6296. if (rightHanded === void 0) { rightHanded = false; }
  6297. var rightHandedFactor = rightHanded ? -1 : 1;
  6298. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6299. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6300. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6301. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6302. var xScale = 2.0 / (leftTan + rightTan);
  6303. var yScale = 2.0 / (upTan + downTan);
  6304. result.m[0] = xScale;
  6305. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6306. result.m[5] = yScale;
  6307. result.m[6] = result.m[7] = 0.0;
  6308. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6309. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6310. result.m[10] = -zfar / (znear - zfar);
  6311. result.m[11] = 1.0 * rightHandedFactor;
  6312. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6313. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6314. result._markAsUpdated();
  6315. };
  6316. /**
  6317. * Computes a complete transformation matrix
  6318. * @param viewport defines the viewport to use
  6319. * @param world defines the world matrix
  6320. * @param view defines the view matrix
  6321. * @param projection defines the projection matrix
  6322. * @param zmin defines the near clip plane
  6323. * @param zmax defines the far clip plane
  6324. * @returns the transformation matrix
  6325. */
  6326. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6327. var cw = viewport.width;
  6328. var ch = viewport.height;
  6329. var cx = viewport.x;
  6330. var cy = viewport.y;
  6331. 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);
  6332. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6333. };
  6334. /**
  6335. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6336. * @param matrix defines the matrix to use
  6337. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6338. */
  6339. Matrix.GetAsMatrix2x2 = function (matrix) {
  6340. return new Float32Array([
  6341. matrix.m[0], matrix.m[1],
  6342. matrix.m[4], matrix.m[5]
  6343. ]);
  6344. };
  6345. /**
  6346. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6347. * @param matrix defines the matrix to use
  6348. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6349. */
  6350. Matrix.GetAsMatrix3x3 = function (matrix) {
  6351. return new Float32Array([
  6352. matrix.m[0], matrix.m[1], matrix.m[2],
  6353. matrix.m[4], matrix.m[5], matrix.m[6],
  6354. matrix.m[8], matrix.m[9], matrix.m[10]
  6355. ]);
  6356. };
  6357. /**
  6358. * Compute the transpose of a given matrix
  6359. * @param matrix defines the matrix to transpose
  6360. * @returns the new matrix
  6361. */
  6362. Matrix.Transpose = function (matrix) {
  6363. var result = new Matrix();
  6364. Matrix.TransposeToRef(matrix, result);
  6365. return result;
  6366. };
  6367. /**
  6368. * Compute the transpose of a matrix and store it in a target matrix
  6369. * @param matrix defines the matrix to transpose
  6370. * @param result defines the target matrix
  6371. */
  6372. Matrix.TransposeToRef = function (matrix, result) {
  6373. result.m[0] = matrix.m[0];
  6374. result.m[1] = matrix.m[4];
  6375. result.m[2] = matrix.m[8];
  6376. result.m[3] = matrix.m[12];
  6377. result.m[4] = matrix.m[1];
  6378. result.m[5] = matrix.m[5];
  6379. result.m[6] = matrix.m[9];
  6380. result.m[7] = matrix.m[13];
  6381. result.m[8] = matrix.m[2];
  6382. result.m[9] = matrix.m[6];
  6383. result.m[10] = matrix.m[10];
  6384. result.m[11] = matrix.m[14];
  6385. result.m[12] = matrix.m[3];
  6386. result.m[13] = matrix.m[7];
  6387. result.m[14] = matrix.m[11];
  6388. result.m[15] = matrix.m[15];
  6389. };
  6390. /**
  6391. * Computes a reflection matrix from a plane
  6392. * @param plane defines the reflection plane
  6393. * @returns a new matrix
  6394. */
  6395. Matrix.Reflection = function (plane) {
  6396. var matrix = new Matrix();
  6397. Matrix.ReflectionToRef(plane, matrix);
  6398. return matrix;
  6399. };
  6400. /**
  6401. * Computes a reflection matrix from a plane
  6402. * @param plane defines the reflection plane
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.ReflectionToRef = function (plane, result) {
  6406. plane.normalize();
  6407. var x = plane.normal.x;
  6408. var y = plane.normal.y;
  6409. var z = plane.normal.z;
  6410. var temp = -2 * x;
  6411. var temp2 = -2 * y;
  6412. var temp3 = -2 * z;
  6413. result.m[0] = (temp * x) + 1;
  6414. result.m[1] = temp2 * x;
  6415. result.m[2] = temp3 * x;
  6416. result.m[3] = 0.0;
  6417. result.m[4] = temp * y;
  6418. result.m[5] = (temp2 * y) + 1;
  6419. result.m[6] = temp3 * y;
  6420. result.m[7] = 0.0;
  6421. result.m[8] = temp * z;
  6422. result.m[9] = temp2 * z;
  6423. result.m[10] = (temp3 * z) + 1;
  6424. result.m[11] = 0.0;
  6425. result.m[12] = temp * plane.d;
  6426. result.m[13] = temp2 * plane.d;
  6427. result.m[14] = temp3 * plane.d;
  6428. result.m[15] = 1.0;
  6429. result._markAsUpdated();
  6430. };
  6431. /**
  6432. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6433. * @param xaxis defines the value of the 1st axis
  6434. * @param yaxis defines the value of the 2nd axis
  6435. * @param zaxis defines the value of the 3rd axis
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6439. result.m[0] = xaxis.x;
  6440. result.m[1] = xaxis.y;
  6441. result.m[2] = xaxis.z;
  6442. result.m[3] = 0.0;
  6443. result.m[4] = yaxis.x;
  6444. result.m[5] = yaxis.y;
  6445. result.m[6] = yaxis.z;
  6446. result.m[7] = 0.0;
  6447. result.m[8] = zaxis.x;
  6448. result.m[9] = zaxis.y;
  6449. result.m[10] = zaxis.z;
  6450. result.m[11] = 0.0;
  6451. result.m[12] = 0.0;
  6452. result.m[13] = 0.0;
  6453. result.m[14] = 0.0;
  6454. result.m[15] = 1.0;
  6455. result._markAsUpdated();
  6456. };
  6457. /**
  6458. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6459. * @param quat defines the quaternion to use
  6460. * @param result defines the target matrix
  6461. */
  6462. Matrix.FromQuaternionToRef = function (quat, result) {
  6463. var xx = quat.x * quat.x;
  6464. var yy = quat.y * quat.y;
  6465. var zz = quat.z * quat.z;
  6466. var xy = quat.x * quat.y;
  6467. var zw = quat.z * quat.w;
  6468. var zx = quat.z * quat.x;
  6469. var yw = quat.y * quat.w;
  6470. var yz = quat.y * quat.z;
  6471. var xw = quat.x * quat.w;
  6472. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6473. result.m[1] = 2.0 * (xy + zw);
  6474. result.m[2] = 2.0 * (zx - yw);
  6475. result.m[3] = 0.0;
  6476. result.m[4] = 2.0 * (xy - zw);
  6477. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6478. result.m[6] = 2.0 * (yz + xw);
  6479. result.m[7] = 0.0;
  6480. result.m[8] = 2.0 * (zx + yw);
  6481. result.m[9] = 2.0 * (yz - xw);
  6482. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. Matrix._tempQuaternion = new Quaternion();
  6491. Matrix._xAxis = Vector3.Zero();
  6492. Matrix._yAxis = Vector3.Zero();
  6493. Matrix._zAxis = Vector3.Zero();
  6494. Matrix._updateFlagSeed = 0;
  6495. Matrix._identityReadOnly = Matrix.Identity();
  6496. return Matrix;
  6497. }());
  6498. BABYLON.Matrix = Matrix;
  6499. var Plane = /** @class */ (function () {
  6500. /**
  6501. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6502. */
  6503. function Plane(a, b, c, d) {
  6504. this.normal = new Vector3(a, b, c);
  6505. this.d = d;
  6506. }
  6507. /**
  6508. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6509. */
  6510. Plane.prototype.asArray = function () {
  6511. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6512. };
  6513. // Methods
  6514. /**
  6515. * Returns a new plane copied from the current Plane.
  6516. */
  6517. Plane.prototype.clone = function () {
  6518. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6519. };
  6520. /**
  6521. * Returns the string "Plane".
  6522. */
  6523. Plane.prototype.getClassName = function () {
  6524. return "Plane";
  6525. };
  6526. /**
  6527. * Returns the Plane hash code.
  6528. */
  6529. Plane.prototype.getHashCode = function () {
  6530. var hash = this.normal.getHashCode();
  6531. hash = (hash * 397) ^ (this.d || 0);
  6532. return hash;
  6533. };
  6534. /**
  6535. * Normalize the current Plane in place.
  6536. * Returns the updated Plane.
  6537. */
  6538. Plane.prototype.normalize = function () {
  6539. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6540. var magnitude = 0.0;
  6541. if (norm !== 0) {
  6542. magnitude = 1.0 / norm;
  6543. }
  6544. this.normal.x *= magnitude;
  6545. this.normal.y *= magnitude;
  6546. this.normal.z *= magnitude;
  6547. this.d *= magnitude;
  6548. return this;
  6549. };
  6550. /**
  6551. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6552. */
  6553. Plane.prototype.transform = function (transformation) {
  6554. var transposedMatrix = Matrix.Transpose(transformation);
  6555. var x = this.normal.x;
  6556. var y = this.normal.y;
  6557. var z = this.normal.z;
  6558. var d = this.d;
  6559. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6560. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6561. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6562. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6563. return new Plane(normalX, normalY, normalZ, finalD);
  6564. };
  6565. /**
  6566. * Returns the dot product (float) of the point coordinates and the plane normal.
  6567. */
  6568. Plane.prototype.dotCoordinate = function (point) {
  6569. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6570. };
  6571. /**
  6572. * Updates the current Plane from the plane defined by the three given points.
  6573. * Returns the updated Plane.
  6574. */
  6575. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6576. var x1 = point2.x - point1.x;
  6577. var y1 = point2.y - point1.y;
  6578. var z1 = point2.z - point1.z;
  6579. var x2 = point3.x - point1.x;
  6580. var y2 = point3.y - point1.y;
  6581. var z2 = point3.z - point1.z;
  6582. var yz = (y1 * z2) - (z1 * y2);
  6583. var xz = (z1 * x2) - (x1 * z2);
  6584. var xy = (x1 * y2) - (y1 * x2);
  6585. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6586. var invPyth;
  6587. if (pyth !== 0) {
  6588. invPyth = 1.0 / pyth;
  6589. }
  6590. else {
  6591. invPyth = 0.0;
  6592. }
  6593. this.normal.x = yz * invPyth;
  6594. this.normal.y = xz * invPyth;
  6595. this.normal.z = xy * invPyth;
  6596. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6597. return this;
  6598. };
  6599. /**
  6600. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6601. */
  6602. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6603. var dot = Vector3.Dot(this.normal, direction);
  6604. return (dot <= epsilon);
  6605. };
  6606. /**
  6607. * Returns the signed distance (float) from the given point to the Plane.
  6608. */
  6609. Plane.prototype.signedDistanceTo = function (point) {
  6610. return Vector3.Dot(point, this.normal) + this.d;
  6611. };
  6612. // Statics
  6613. /**
  6614. * Returns a new Plane from the given array.
  6615. */
  6616. Plane.FromArray = function (array) {
  6617. return new Plane(array[0], array[1], array[2], array[3]);
  6618. };
  6619. /**
  6620. * Returns a new Plane defined by the three given points.
  6621. */
  6622. Plane.FromPoints = function (point1, point2, point3) {
  6623. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6624. result.copyFromPoints(point1, point2, point3);
  6625. return result;
  6626. };
  6627. /**
  6628. * Returns a new Plane the normal vector to this plane at the given origin point.
  6629. * Note : the vector "normal" is updated because normalized.
  6630. */
  6631. Plane.FromPositionAndNormal = function (origin, normal) {
  6632. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6633. normal.normalize();
  6634. result.normal = normal;
  6635. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6636. return result;
  6637. };
  6638. /**
  6639. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6640. */
  6641. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6642. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6643. return Vector3.Dot(point, normal) + d;
  6644. };
  6645. return Plane;
  6646. }());
  6647. BABYLON.Plane = Plane;
  6648. var Viewport = /** @class */ (function () {
  6649. /**
  6650. * Creates a Viewport object located at (x, y) and sized (width, height).
  6651. */
  6652. function Viewport(x, y, width, height) {
  6653. this.x = x;
  6654. this.y = y;
  6655. this.width = width;
  6656. this.height = height;
  6657. }
  6658. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6659. if (renderWidthOrEngine.getRenderWidth) {
  6660. var engine = renderWidthOrEngine;
  6661. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6662. }
  6663. var renderWidth = renderWidthOrEngine;
  6664. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6665. };
  6666. /**
  6667. * Returns a new Viewport copied from the current one.
  6668. */
  6669. Viewport.prototype.clone = function () {
  6670. return new Viewport(this.x, this.y, this.width, this.height);
  6671. };
  6672. return Viewport;
  6673. }());
  6674. BABYLON.Viewport = Viewport;
  6675. var Frustum = /** @class */ (function () {
  6676. function Frustum() {
  6677. }
  6678. /**
  6679. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6680. */
  6681. Frustum.GetPlanes = function (transform) {
  6682. var frustumPlanes = [];
  6683. for (var index = 0; index < 6; index++) {
  6684. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6685. }
  6686. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6687. return frustumPlanes;
  6688. };
  6689. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6690. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6691. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6692. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6693. frustumPlane.d = transform.m[15] + transform.m[14];
  6694. frustumPlane.normalize();
  6695. };
  6696. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6697. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6698. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6699. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6700. frustumPlane.d = transform.m[15] - transform.m[14];
  6701. frustumPlane.normalize();
  6702. };
  6703. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6704. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6705. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6706. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6707. frustumPlane.d = transform.m[15] + transform.m[12];
  6708. frustumPlane.normalize();
  6709. };
  6710. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6711. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6712. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6713. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6714. frustumPlane.d = transform.m[15] - transform.m[12];
  6715. frustumPlane.normalize();
  6716. };
  6717. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6718. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6719. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6720. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6721. frustumPlane.d = transform.m[15] - transform.m[13];
  6722. frustumPlane.normalize();
  6723. };
  6724. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6725. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6726. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6727. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6728. frustumPlane.d = transform.m[15] + transform.m[13];
  6729. frustumPlane.normalize();
  6730. };
  6731. /**
  6732. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6733. */
  6734. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6735. // Near
  6736. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6737. // Far
  6738. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6739. // Left
  6740. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6741. // Right
  6742. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6743. // Top
  6744. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6745. // Bottom
  6746. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6747. };
  6748. return Frustum;
  6749. }());
  6750. BABYLON.Frustum = Frustum;
  6751. var Space;
  6752. (function (Space) {
  6753. Space[Space["LOCAL"] = 0] = "LOCAL";
  6754. Space[Space["WORLD"] = 1] = "WORLD";
  6755. Space[Space["BONE"] = 2] = "BONE";
  6756. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6757. var Axis = /** @class */ (function () {
  6758. function Axis() {
  6759. }
  6760. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6761. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6762. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6763. return Axis;
  6764. }());
  6765. BABYLON.Axis = Axis;
  6766. ;
  6767. var BezierCurve = /** @class */ (function () {
  6768. function BezierCurve() {
  6769. }
  6770. /**
  6771. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6772. */
  6773. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6774. // Extract X (which is equal to time here)
  6775. var f0 = 1 - 3 * x2 + 3 * x1;
  6776. var f1 = 3 * x2 - 6 * x1;
  6777. var f2 = 3 * x1;
  6778. var refinedT = t;
  6779. for (var i = 0; i < 5; i++) {
  6780. var refinedT2 = refinedT * refinedT;
  6781. var refinedT3 = refinedT2 * refinedT;
  6782. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6783. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6784. refinedT -= (x - t) * slope;
  6785. refinedT = Math.min(1, Math.max(0, refinedT));
  6786. }
  6787. // Resolve cubic bezier for the given x
  6788. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6789. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6790. Math.pow(refinedT, 3);
  6791. };
  6792. return BezierCurve;
  6793. }());
  6794. BABYLON.BezierCurve = BezierCurve;
  6795. var Orientation;
  6796. (function (Orientation) {
  6797. Orientation[Orientation["CW"] = 0] = "CW";
  6798. Orientation[Orientation["CCW"] = 1] = "CCW";
  6799. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6800. var Angle = /** @class */ (function () {
  6801. /**
  6802. * Creates an Angle object of "radians" radians (float).
  6803. */
  6804. function Angle(radians) {
  6805. var _this = this;
  6806. /**
  6807. * Returns the Angle value in degrees (float).
  6808. */
  6809. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6810. /**
  6811. * Returns the Angle value in radians (float).
  6812. */
  6813. this.radians = function () { return _this._radians; };
  6814. this._radians = radians;
  6815. if (this._radians < 0.0)
  6816. this._radians += (2.0 * Math.PI);
  6817. }
  6818. /**
  6819. * Returns a new Angle object valued with the angle value in radians between the two given vectors.
  6820. */
  6821. Angle.BetweenTwoPoints = function (a, b) {
  6822. var delta = b.subtract(a);
  6823. var theta = Math.atan2(delta.y, delta.x);
  6824. return new Angle(theta);
  6825. };
  6826. /**
  6827. * Returns a new Angle object from the given float in radians.
  6828. */
  6829. Angle.FromRadians = function (radians) {
  6830. return new Angle(radians);
  6831. };
  6832. /**
  6833. * Returns a new Angle object from the given float in degrees.
  6834. */
  6835. Angle.FromDegrees = function (degrees) {
  6836. return new Angle(degrees * Math.PI / 180.0);
  6837. };
  6838. return Angle;
  6839. }());
  6840. BABYLON.Angle = Angle;
  6841. var Arc2 = /** @class */ (function () {
  6842. /**
  6843. * Creates an Arc object from the three given points : start, middle and end.
  6844. */
  6845. function Arc2(startPoint, midPoint, endPoint) {
  6846. this.startPoint = startPoint;
  6847. this.midPoint = midPoint;
  6848. this.endPoint = endPoint;
  6849. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6850. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6851. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6852. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6853. 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);
  6854. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6855. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6856. var a1 = this.startAngle.degrees();
  6857. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6858. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6859. // angles correction
  6860. if (a2 - a1 > +180.0)
  6861. a2 -= 360.0;
  6862. if (a2 - a1 < -180.0)
  6863. a2 += 360.0;
  6864. if (a3 - a2 > +180.0)
  6865. a3 -= 360.0;
  6866. if (a3 - a2 < -180.0)
  6867. a3 += 360.0;
  6868. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6869. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6870. }
  6871. return Arc2;
  6872. }());
  6873. BABYLON.Arc2 = Arc2;
  6874. var Path2 = /** @class */ (function () {
  6875. /**
  6876. * Creates a Path2 object from the starting 2D coordinates x and y.
  6877. */
  6878. function Path2(x, y) {
  6879. this._points = new Array();
  6880. this._length = 0.0;
  6881. this.closed = false;
  6882. this._points.push(new Vector2(x, y));
  6883. }
  6884. /**
  6885. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6886. * Returns the updated Path2.
  6887. */
  6888. Path2.prototype.addLineTo = function (x, y) {
  6889. if (this.closed) {
  6890. return this;
  6891. }
  6892. var newPoint = new Vector2(x, y);
  6893. var previousPoint = this._points[this._points.length - 1];
  6894. this._points.push(newPoint);
  6895. this._length += newPoint.subtract(previousPoint).length();
  6896. return this;
  6897. };
  6898. /**
  6899. * 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.
  6900. * Returns the updated Path2.
  6901. */
  6902. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6903. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6904. if (this.closed) {
  6905. return this;
  6906. }
  6907. var startPoint = this._points[this._points.length - 1];
  6908. var midPoint = new Vector2(midX, midY);
  6909. var endPoint = new Vector2(endX, endY);
  6910. var arc = new Arc2(startPoint, midPoint, endPoint);
  6911. var increment = arc.angle.radians() / numberOfSegments;
  6912. if (arc.orientation === Orientation.CW)
  6913. increment *= -1;
  6914. var currentAngle = arc.startAngle.radians() + increment;
  6915. for (var i = 0; i < numberOfSegments; i++) {
  6916. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6917. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6918. this.addLineTo(x, y);
  6919. currentAngle += increment;
  6920. }
  6921. return this;
  6922. };
  6923. /**
  6924. * Closes the Path2.
  6925. * Returns the Path2.
  6926. */
  6927. Path2.prototype.close = function () {
  6928. this.closed = true;
  6929. return this;
  6930. };
  6931. /**
  6932. * Returns the Path2 total length (float).
  6933. */
  6934. Path2.prototype.length = function () {
  6935. var result = this._length;
  6936. if (!this.closed) {
  6937. var lastPoint = this._points[this._points.length - 1];
  6938. var firstPoint = this._points[0];
  6939. result += (firstPoint.subtract(lastPoint).length());
  6940. }
  6941. return result;
  6942. };
  6943. /**
  6944. * Returns the Path2 internal array of points.
  6945. */
  6946. Path2.prototype.getPoints = function () {
  6947. return this._points;
  6948. };
  6949. /**
  6950. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6951. */
  6952. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6953. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6954. return Vector2.Zero();
  6955. }
  6956. var lengthPosition = normalizedLengthPosition * this.length();
  6957. var previousOffset = 0;
  6958. for (var i = 0; i < this._points.length; i++) {
  6959. var j = (i + 1) % this._points.length;
  6960. var a = this._points[i];
  6961. var b = this._points[j];
  6962. var bToA = b.subtract(a);
  6963. var nextOffset = (bToA.length() + previousOffset);
  6964. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6965. var dir = bToA.normalize();
  6966. var localOffset = lengthPosition - previousOffset;
  6967. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6968. }
  6969. previousOffset = nextOffset;
  6970. }
  6971. return Vector2.Zero();
  6972. };
  6973. /**
  6974. * Returns a new Path2 starting at the coordinates (x, y).
  6975. */
  6976. Path2.StartingAt = function (x, y) {
  6977. return new Path2(x, y);
  6978. };
  6979. return Path2;
  6980. }());
  6981. BABYLON.Path2 = Path2;
  6982. var Path3D = /** @class */ (function () {
  6983. /**
  6984. * new Path3D(path, normal, raw)
  6985. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6986. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6987. * path : an array of Vector3, the curve axis of the Path3D
  6988. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6989. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6990. */
  6991. function Path3D(path, firstNormal, raw) {
  6992. if (firstNormal === void 0) { firstNormal = null; }
  6993. this.path = path;
  6994. this._curve = new Array();
  6995. this._distances = new Array();
  6996. this._tangents = new Array();
  6997. this._normals = new Array();
  6998. this._binormals = new Array();
  6999. for (var p = 0; p < path.length; p++) {
  7000. this._curve[p] = path[p].clone(); // hard copy
  7001. }
  7002. this._raw = raw || false;
  7003. this._compute(firstNormal);
  7004. }
  7005. /**
  7006. * Returns the Path3D array of successive Vector3 designing its curve.
  7007. */
  7008. Path3D.prototype.getCurve = function () {
  7009. return this._curve;
  7010. };
  7011. /**
  7012. * Returns an array populated with tangent vectors on each Path3D curve point.
  7013. */
  7014. Path3D.prototype.getTangents = function () {
  7015. return this._tangents;
  7016. };
  7017. /**
  7018. * Returns an array populated with normal vectors on each Path3D curve point.
  7019. */
  7020. Path3D.prototype.getNormals = function () {
  7021. return this._normals;
  7022. };
  7023. /**
  7024. * Returns an array populated with binormal vectors on each Path3D curve point.
  7025. */
  7026. Path3D.prototype.getBinormals = function () {
  7027. return this._binormals;
  7028. };
  7029. /**
  7030. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7031. */
  7032. Path3D.prototype.getDistances = function () {
  7033. return this._distances;
  7034. };
  7035. /**
  7036. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7037. * Returns the same object updated.
  7038. */
  7039. Path3D.prototype.update = function (path, firstNormal) {
  7040. if (firstNormal === void 0) { firstNormal = null; }
  7041. for (var p = 0; p < path.length; p++) {
  7042. this._curve[p].x = path[p].x;
  7043. this._curve[p].y = path[p].y;
  7044. this._curve[p].z = path[p].z;
  7045. }
  7046. this._compute(firstNormal);
  7047. return this;
  7048. };
  7049. // private function compute() : computes tangents, normals and binormals
  7050. Path3D.prototype._compute = function (firstNormal) {
  7051. var l = this._curve.length;
  7052. // first and last tangents
  7053. this._tangents[0] = this._getFirstNonNullVector(0);
  7054. if (!this._raw) {
  7055. this._tangents[0].normalize();
  7056. }
  7057. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7058. if (!this._raw) {
  7059. this._tangents[l - 1].normalize();
  7060. }
  7061. // normals and binormals at first point : arbitrary vector with _normalVector()
  7062. var tg0 = this._tangents[0];
  7063. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7064. this._normals[0] = pp0;
  7065. if (!this._raw) {
  7066. this._normals[0].normalize();
  7067. }
  7068. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7069. if (!this._raw) {
  7070. this._binormals[0].normalize();
  7071. }
  7072. this._distances[0] = 0.0;
  7073. // normals and binormals : next points
  7074. var prev; // previous vector (segment)
  7075. var cur; // current vector (segment)
  7076. var curTang; // current tangent
  7077. // previous normal
  7078. var prevBinor; // previous binormal
  7079. for (var i = 1; i < l; i++) {
  7080. // tangents
  7081. prev = this._getLastNonNullVector(i);
  7082. if (i < l - 1) {
  7083. cur = this._getFirstNonNullVector(i);
  7084. this._tangents[i] = prev.add(cur);
  7085. this._tangents[i].normalize();
  7086. }
  7087. this._distances[i] = this._distances[i - 1] + prev.length();
  7088. // normals and binormals
  7089. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7090. curTang = this._tangents[i];
  7091. prevBinor = this._binormals[i - 1];
  7092. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7093. if (!this._raw) {
  7094. this._normals[i].normalize();
  7095. }
  7096. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7097. if (!this._raw) {
  7098. this._binormals[i].normalize();
  7099. }
  7100. }
  7101. };
  7102. // private function getFirstNonNullVector(index)
  7103. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7104. Path3D.prototype._getFirstNonNullVector = function (index) {
  7105. var i = 1;
  7106. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7107. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7108. i++;
  7109. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7110. }
  7111. return nNVector;
  7112. };
  7113. // private function getLastNonNullVector(index)
  7114. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7115. Path3D.prototype._getLastNonNullVector = function (index) {
  7116. var i = 1;
  7117. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7118. while (nLVector.length() === 0 && index > i + 1) {
  7119. i++;
  7120. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7121. }
  7122. return nLVector;
  7123. };
  7124. // private function normalVector(v0, vt, va) :
  7125. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7126. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7127. Path3D.prototype._normalVector = function (v0, vt, va) {
  7128. var normal0;
  7129. var tgl = vt.length();
  7130. if (tgl === 0.0) {
  7131. tgl = 1.0;
  7132. }
  7133. if (va === undefined || va === null) {
  7134. var point;
  7135. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  7136. point = new Vector3(0.0, -1.0, 0.0);
  7137. }
  7138. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7139. point = new Vector3(1.0, 0.0, 0.0);
  7140. }
  7141. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7142. point = new Vector3(0.0, 0.0, 1.0);
  7143. }
  7144. else {
  7145. point = Vector3.Zero();
  7146. }
  7147. normal0 = Vector3.Cross(vt, point);
  7148. }
  7149. else {
  7150. normal0 = Vector3.Cross(vt, va);
  7151. Vector3.CrossToRef(normal0, vt, normal0);
  7152. }
  7153. normal0.normalize();
  7154. return normal0;
  7155. };
  7156. return Path3D;
  7157. }());
  7158. BABYLON.Path3D = Path3D;
  7159. var Curve3 = /** @class */ (function () {
  7160. /**
  7161. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7162. * A Curve3 is designed from a series of successive Vector3.
  7163. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7164. */
  7165. function Curve3(points) {
  7166. this._length = 0.0;
  7167. this._points = points;
  7168. this._length = this._computeLength(points);
  7169. }
  7170. /**
  7171. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7172. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7173. * @param v1 (Vector3) the control point
  7174. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7175. * @param nbPoints (integer) the wanted number of points in the curve
  7176. */
  7177. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7178. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7179. var bez = new Array();
  7180. var equation = function (t, val0, val1, val2) {
  7181. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7182. return res;
  7183. };
  7184. for (var i = 0; i <= nbPoints; i++) {
  7185. 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)));
  7186. }
  7187. return new Curve3(bez);
  7188. };
  7189. /**
  7190. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7191. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7192. * @param v1 (Vector3) the first control point
  7193. * @param v2 (Vector3) the second control point
  7194. * @param v3 (Vector3) the end point of the Cubic Bezier
  7195. * @param nbPoints (integer) the wanted number of points in the curve
  7196. */
  7197. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7198. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7199. var bez = new Array();
  7200. var equation = function (t, val0, val1, val2, val3) {
  7201. 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;
  7202. return res;
  7203. };
  7204. for (var i = 0; i <= nbPoints; i++) {
  7205. 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)));
  7206. }
  7207. return new Curve3(bez);
  7208. };
  7209. /**
  7210. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7211. * @param p1 (Vector3) the origin point of the Hermite Spline
  7212. * @param t1 (Vector3) the tangent vector at the origin point
  7213. * @param p2 (Vector3) the end point of the Hermite Spline
  7214. * @param t2 (Vector3) the tangent vector at the end point
  7215. * @param nbPoints (integer) the wanted number of points in the curve
  7216. */
  7217. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7218. var hermite = new Array();
  7219. var step = 1.0 / nbPoints;
  7220. for (var i = 0; i <= nbPoints; i++) {
  7221. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7222. }
  7223. return new Curve3(hermite);
  7224. };
  7225. /**
  7226. * Returns a Curve3 object along a CatmullRom Spline curve :
  7227. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7228. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7229. */
  7230. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7231. var totalPoints = new Array();
  7232. totalPoints.push(points[0].clone());
  7233. Array.prototype.push.apply(totalPoints, points);
  7234. totalPoints.push(points[points.length - 1].clone());
  7235. var catmullRom = new Array();
  7236. var step = 1.0 / nbPoints;
  7237. var amount = 0.0;
  7238. for (var i = 0; i < totalPoints.length - 3; i++) {
  7239. amount = 0;
  7240. for (var c = 0; c < nbPoints; c++) {
  7241. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7242. amount += step;
  7243. }
  7244. }
  7245. i--;
  7246. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7247. return new Curve3(catmullRom);
  7248. };
  7249. /**
  7250. * Returns the Curve3 stored array of successive Vector3
  7251. */
  7252. Curve3.prototype.getPoints = function () {
  7253. return this._points;
  7254. };
  7255. /**
  7256. * Returns the computed length (float) of the curve.
  7257. */
  7258. Curve3.prototype.length = function () {
  7259. return this._length;
  7260. };
  7261. /**
  7262. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7263. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7264. * curveA and curveB keep unchanged.
  7265. */
  7266. Curve3.prototype.continue = function (curve) {
  7267. var lastPoint = this._points[this._points.length - 1];
  7268. var continuedPoints = this._points.slice();
  7269. var curvePoints = curve.getPoints();
  7270. for (var i = 1; i < curvePoints.length; i++) {
  7271. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7272. }
  7273. var continuedCurve = new Curve3(continuedPoints);
  7274. return continuedCurve;
  7275. };
  7276. Curve3.prototype._computeLength = function (path) {
  7277. var l = 0;
  7278. for (var i = 1; i < path.length; i++) {
  7279. l += (path[i].subtract(path[i - 1])).length();
  7280. }
  7281. return l;
  7282. };
  7283. return Curve3;
  7284. }());
  7285. BABYLON.Curve3 = Curve3;
  7286. // Vertex formats
  7287. var PositionNormalVertex = /** @class */ (function () {
  7288. function PositionNormalVertex(position, normal) {
  7289. if (position === void 0) { position = Vector3.Zero(); }
  7290. if (normal === void 0) { normal = Vector3.Up(); }
  7291. this.position = position;
  7292. this.normal = normal;
  7293. }
  7294. PositionNormalVertex.prototype.clone = function () {
  7295. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7296. };
  7297. return PositionNormalVertex;
  7298. }());
  7299. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7300. var PositionNormalTextureVertex = /** @class */ (function () {
  7301. function PositionNormalTextureVertex(position, normal, uv) {
  7302. if (position === void 0) { position = Vector3.Zero(); }
  7303. if (normal === void 0) { normal = Vector3.Up(); }
  7304. if (uv === void 0) { uv = Vector2.Zero(); }
  7305. this.position = position;
  7306. this.normal = normal;
  7307. this.uv = uv;
  7308. }
  7309. PositionNormalTextureVertex.prototype.clone = function () {
  7310. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7311. };
  7312. return PositionNormalTextureVertex;
  7313. }());
  7314. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7315. // Temporary pre-allocated objects for engine internal use
  7316. // usage in any internal function :
  7317. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7318. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7319. var Tmp = /** @class */ (function () {
  7320. function Tmp() {
  7321. }
  7322. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7323. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7324. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7325. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7326. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7327. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7328. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7329. Matrix.Zero(), Matrix.Zero(),
  7330. Matrix.Zero(), Matrix.Zero(),
  7331. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7332. return Tmp;
  7333. }());
  7334. BABYLON.Tmp = Tmp;
  7335. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7336. var MathTmp = /** @class */ (function () {
  7337. function MathTmp() {
  7338. }
  7339. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7340. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7341. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7342. return MathTmp;
  7343. }());
  7344. })(BABYLON || (BABYLON = {}));
  7345. //# sourceMappingURL=babylon.math.js.map
  7346. "use strict";
  7347. var BABYLON;
  7348. (function (BABYLON) {
  7349. var Scalar = /** @class */ (function () {
  7350. function Scalar() {
  7351. }
  7352. /**
  7353. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7354. */
  7355. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7356. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7357. var num = a - b;
  7358. return -epsilon <= num && num <= epsilon;
  7359. };
  7360. /**
  7361. * Returns a string : the upper case translation of the number i to hexadecimal.
  7362. */
  7363. Scalar.ToHex = function (i) {
  7364. var str = i.toString(16);
  7365. if (i <= 15) {
  7366. return ("0" + str).toUpperCase();
  7367. }
  7368. return str.toUpperCase();
  7369. };
  7370. /**
  7371. * Returns -1 if value is negative and +1 is value is positive.
  7372. * Returns the value itself if it's equal to zero.
  7373. */
  7374. Scalar.Sign = function (value) {
  7375. value = +value; // convert to a number
  7376. if (value === 0 || isNaN(value))
  7377. return value;
  7378. return value > 0 ? 1 : -1;
  7379. };
  7380. /**
  7381. * Returns the value itself if it's between min and max.
  7382. * Returns min if the value is lower than min.
  7383. * Returns max if the value is greater than max.
  7384. */
  7385. Scalar.Clamp = function (value, min, max) {
  7386. if (min === void 0) { min = 0; }
  7387. if (max === void 0) { max = 1; }
  7388. return Math.min(max, Math.max(min, value));
  7389. };
  7390. /**
  7391. * Returns the log2 of value.
  7392. */
  7393. Scalar.Log2 = function (value) {
  7394. return Math.log(value) * Math.LOG2E;
  7395. };
  7396. /**
  7397. * Loops the value, so that it is never larger than length and never smaller than 0.
  7398. *
  7399. * This is similar to the modulo operator but it works with floating point numbers.
  7400. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7401. * With t = 5 and length = 2.5, the result would be 0.0.
  7402. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7403. */
  7404. Scalar.Repeat = function (value, length) {
  7405. return value - Math.floor(value / length) * length;
  7406. };
  7407. /**
  7408. * Normalize the value between 0.0 and 1.0 using min and max values
  7409. */
  7410. Scalar.Normalize = function (value, min, max) {
  7411. return (value - min) / (max - min);
  7412. };
  7413. /**
  7414. * Denormalize the value from 0.0 and 1.0 using min and max values
  7415. */
  7416. Scalar.Denormalize = function (normalized, min, max) {
  7417. return (normalized * (max - min) + min);
  7418. };
  7419. /**
  7420. * Calculates the shortest difference between two given angles given in degrees.
  7421. */
  7422. Scalar.DeltaAngle = function (current, target) {
  7423. var num = Scalar.Repeat(target - current, 360.0);
  7424. if (num > 180.0) {
  7425. num -= 360.0;
  7426. }
  7427. return num;
  7428. };
  7429. /**
  7430. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7431. *
  7432. * The returned value will move back and forth between 0 and length
  7433. */
  7434. Scalar.PingPong = function (tx, length) {
  7435. var t = Scalar.Repeat(tx, length * 2.0);
  7436. return length - Math.abs(t - length);
  7437. };
  7438. /**
  7439. * Interpolates between min and max with smoothing at the limits.
  7440. *
  7441. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7442. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7443. */
  7444. Scalar.SmoothStep = function (from, to, tx) {
  7445. var t = Scalar.Clamp(tx);
  7446. t = -2.0 * t * t * t + 3.0 * t * t;
  7447. return to * t + from * (1.0 - t);
  7448. };
  7449. /**
  7450. * Moves a value current towards target.
  7451. *
  7452. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7453. * Negative values of maxDelta pushes the value away from target.
  7454. */
  7455. Scalar.MoveTowards = function (current, target, maxDelta) {
  7456. var result = 0;
  7457. if (Math.abs(target - current) <= maxDelta) {
  7458. result = target;
  7459. }
  7460. else {
  7461. result = current + Scalar.Sign(target - current) * maxDelta;
  7462. }
  7463. return result;
  7464. };
  7465. /**
  7466. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7467. *
  7468. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7469. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7470. */
  7471. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7472. var num = Scalar.DeltaAngle(current, target);
  7473. var result = 0;
  7474. if (-maxDelta < num && num < maxDelta) {
  7475. result = target;
  7476. }
  7477. else {
  7478. target = current + num;
  7479. result = Scalar.MoveTowards(current, target, maxDelta);
  7480. }
  7481. return result;
  7482. };
  7483. /**
  7484. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7485. */
  7486. Scalar.Lerp = function (start, end, amount) {
  7487. return start + ((end - start) * amount);
  7488. };
  7489. /**
  7490. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7491. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7492. */
  7493. Scalar.LerpAngle = function (start, end, amount) {
  7494. var num = Scalar.Repeat(end - start, 360.0);
  7495. if (num > 180.0) {
  7496. num -= 360.0;
  7497. }
  7498. return start + num * Scalar.Clamp(amount);
  7499. };
  7500. /**
  7501. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7502. */
  7503. Scalar.InverseLerp = function (a, b, value) {
  7504. var result = 0;
  7505. if (a != b) {
  7506. result = Scalar.Clamp((value - a) / (b - a));
  7507. }
  7508. else {
  7509. result = 0.0;
  7510. }
  7511. return result;
  7512. };
  7513. /**
  7514. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7515. */
  7516. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7517. var squared = amount * amount;
  7518. var cubed = amount * squared;
  7519. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7520. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7521. var part3 = (cubed - (2.0 * squared)) + amount;
  7522. var part4 = cubed - squared;
  7523. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7524. };
  7525. /**
  7526. * Returns a random float number between and min and max values
  7527. */
  7528. Scalar.RandomRange = function (min, max) {
  7529. if (min === max)
  7530. return min;
  7531. return ((Math.random() * (max - min)) + min);
  7532. };
  7533. /**
  7534. * This function returns percentage of a number in a given range.
  7535. *
  7536. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7537. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7538. */
  7539. Scalar.RangeToPercent = function (number, min, max) {
  7540. return ((number - min) / (max - min));
  7541. };
  7542. /**
  7543. * This function returns number that corresponds to the percentage in a given range.
  7544. *
  7545. * PercentToRange(0.34,0,100) will return 34.
  7546. */
  7547. Scalar.PercentToRange = function (percent, min, max) {
  7548. return ((max - min) * percent + min);
  7549. };
  7550. /**
  7551. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7552. * @param angle The angle to normalize in radian.
  7553. * @return The converted angle.
  7554. */
  7555. Scalar.NormalizeRadians = function (angle) {
  7556. // More precise but slower version kept for reference.
  7557. // angle = angle % Tools.TwoPi;
  7558. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7559. //if (angle > Math.PI) {
  7560. // angle -= Tools.TwoPi;
  7561. //}
  7562. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7563. return angle;
  7564. };
  7565. /**
  7566. * Two pi constants convenient for computation.
  7567. */
  7568. Scalar.TwoPi = Math.PI * 2;
  7569. return Scalar;
  7570. }());
  7571. BABYLON.Scalar = Scalar;
  7572. })(BABYLON || (BABYLON = {}));
  7573. //# sourceMappingURL=babylon.math.scalar.js.map
  7574. "use strict";
  7575. //# sourceMappingURL=babylon.mixins.js.map
  7576. "use strict";
  7577. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7578. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7579. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7580. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7581. //# sourceMappingURL=babylon.webgl2.js.map
  7582. "use strict";
  7583. var BABYLON;
  7584. (function (BABYLON) {
  7585. var __decoratorInitialStore = {};
  7586. var __mergedStore = {};
  7587. var _copySource = function (creationFunction, source, instanciate) {
  7588. var destination = creationFunction();
  7589. // Tags
  7590. if (BABYLON.Tags) {
  7591. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7592. }
  7593. var classStore = getMergedStore(destination);
  7594. // Properties
  7595. for (var property in classStore) {
  7596. var propertyDescriptor = classStore[property];
  7597. var sourceProperty = source[property];
  7598. var propertyType = propertyDescriptor.type;
  7599. if (sourceProperty !== undefined && sourceProperty !== null) {
  7600. switch (propertyType) {
  7601. case 0: // Value
  7602. case 6: // Mesh reference
  7603. case 11:// Camera reference
  7604. destination[property] = sourceProperty;
  7605. break;
  7606. case 1:// Texture
  7607. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7608. break;
  7609. case 2: // Color3
  7610. case 3: // FresnelParameters
  7611. case 4: // Vector2
  7612. case 5: // Vector3
  7613. case 7: // Color Curves
  7614. case 10:// Quaternion
  7615. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7616. break;
  7617. }
  7618. }
  7619. }
  7620. return destination;
  7621. };
  7622. function getDirectStore(target) {
  7623. var classKey = target.getClassName();
  7624. if (!__decoratorInitialStore[classKey]) {
  7625. __decoratorInitialStore[classKey] = {};
  7626. }
  7627. return __decoratorInitialStore[classKey];
  7628. }
  7629. /**
  7630. * Return the list of properties flagged as serializable
  7631. * @param target: host object
  7632. */
  7633. function getMergedStore(target) {
  7634. var classKey = target.getClassName();
  7635. if (__mergedStore[classKey]) {
  7636. return __mergedStore[classKey];
  7637. }
  7638. __mergedStore[classKey] = {};
  7639. var store = __mergedStore[classKey];
  7640. var currentTarget = target;
  7641. var currentKey = classKey;
  7642. while (currentKey) {
  7643. var initialStore = __decoratorInitialStore[currentKey];
  7644. for (var property in initialStore) {
  7645. store[property] = initialStore[property];
  7646. }
  7647. var parent_1 = void 0;
  7648. var done = false;
  7649. do {
  7650. parent_1 = Object.getPrototypeOf(currentTarget);
  7651. if (!parent_1.getClassName) {
  7652. done = true;
  7653. break;
  7654. }
  7655. if (parent_1.getClassName() !== currentKey) {
  7656. break;
  7657. }
  7658. currentTarget = parent_1;
  7659. } while (parent_1);
  7660. if (done) {
  7661. break;
  7662. }
  7663. currentKey = parent_1.getClassName();
  7664. currentTarget = parent_1;
  7665. }
  7666. return store;
  7667. }
  7668. function generateSerializableMember(type, sourceName) {
  7669. return function (target, propertyKey) {
  7670. var classStore = getDirectStore(target);
  7671. if (!classStore[propertyKey]) {
  7672. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7673. }
  7674. };
  7675. }
  7676. function generateExpandMember(setCallback, targetKey) {
  7677. if (targetKey === void 0) { targetKey = null; }
  7678. return function (target, propertyKey) {
  7679. var key = targetKey || ("_" + propertyKey);
  7680. Object.defineProperty(target, propertyKey, {
  7681. get: function () {
  7682. return this[key];
  7683. },
  7684. set: function (value) {
  7685. if (this[key] === value) {
  7686. return;
  7687. }
  7688. this[key] = value;
  7689. target[setCallback].apply(this);
  7690. },
  7691. enumerable: true,
  7692. configurable: true
  7693. });
  7694. };
  7695. }
  7696. function expandToProperty(callback, targetKey) {
  7697. if (targetKey === void 0) { targetKey = null; }
  7698. return generateExpandMember(callback, targetKey);
  7699. }
  7700. BABYLON.expandToProperty = expandToProperty;
  7701. function serialize(sourceName) {
  7702. return generateSerializableMember(0, sourceName); // value member
  7703. }
  7704. BABYLON.serialize = serialize;
  7705. function serializeAsTexture(sourceName) {
  7706. return generateSerializableMember(1, sourceName); // texture member
  7707. }
  7708. BABYLON.serializeAsTexture = serializeAsTexture;
  7709. function serializeAsColor3(sourceName) {
  7710. return generateSerializableMember(2, sourceName); // color3 member
  7711. }
  7712. BABYLON.serializeAsColor3 = serializeAsColor3;
  7713. function serializeAsFresnelParameters(sourceName) {
  7714. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7715. }
  7716. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7717. function serializeAsVector2(sourceName) {
  7718. return generateSerializableMember(4, sourceName); // vector2 member
  7719. }
  7720. BABYLON.serializeAsVector2 = serializeAsVector2;
  7721. function serializeAsVector3(sourceName) {
  7722. return generateSerializableMember(5, sourceName); // vector3 member
  7723. }
  7724. BABYLON.serializeAsVector3 = serializeAsVector3;
  7725. function serializeAsMeshReference(sourceName) {
  7726. return generateSerializableMember(6, sourceName); // mesh reference member
  7727. }
  7728. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7729. function serializeAsColorCurves(sourceName) {
  7730. return generateSerializableMember(7, sourceName); // color curves
  7731. }
  7732. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7733. function serializeAsColor4(sourceName) {
  7734. return generateSerializableMember(8, sourceName); // color 4
  7735. }
  7736. BABYLON.serializeAsColor4 = serializeAsColor4;
  7737. function serializeAsImageProcessingConfiguration(sourceName) {
  7738. return generateSerializableMember(9, sourceName); // image processing
  7739. }
  7740. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7741. function serializeAsQuaternion(sourceName) {
  7742. return generateSerializableMember(10, sourceName); // quaternion member
  7743. }
  7744. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7745. /**
  7746. * Decorator used to define property that can be serialized as reference to a camera
  7747. * @param sourceName defines the name of the property to decorate
  7748. */
  7749. function serializeAsCameraReference(sourceName) {
  7750. return generateSerializableMember(11, sourceName); // camera reference member
  7751. }
  7752. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7753. var SerializationHelper = /** @class */ (function () {
  7754. function SerializationHelper() {
  7755. }
  7756. SerializationHelper.Serialize = function (entity, serializationObject) {
  7757. if (!serializationObject) {
  7758. serializationObject = {};
  7759. }
  7760. // Tags
  7761. if (BABYLON.Tags) {
  7762. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7763. }
  7764. var serializedProperties = getMergedStore(entity);
  7765. // Properties
  7766. for (var property in serializedProperties) {
  7767. var propertyDescriptor = serializedProperties[property];
  7768. var targetPropertyName = propertyDescriptor.sourceName || property;
  7769. var propertyType = propertyDescriptor.type;
  7770. var sourceProperty = entity[property];
  7771. if (sourceProperty !== undefined && sourceProperty !== null) {
  7772. switch (propertyType) {
  7773. case 0:// Value
  7774. serializationObject[targetPropertyName] = sourceProperty;
  7775. break;
  7776. case 1:// Texture
  7777. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7778. break;
  7779. case 2:// Color3
  7780. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7781. break;
  7782. case 3:// FresnelParameters
  7783. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7784. break;
  7785. case 4:// Vector2
  7786. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7787. break;
  7788. case 5:// Vector3
  7789. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7790. break;
  7791. case 6:// Mesh reference
  7792. serializationObject[targetPropertyName] = sourceProperty.id;
  7793. break;
  7794. case 7:// Color Curves
  7795. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7796. break;
  7797. case 8:// Color 4
  7798. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7799. break;
  7800. case 9:// Image Processing
  7801. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7802. break;
  7803. case 10:// Quaternion
  7804. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7805. break;
  7806. case 11:// Camera reference
  7807. serializationObject[targetPropertyName] = sourceProperty.id;
  7808. break;
  7809. }
  7810. }
  7811. }
  7812. return serializationObject;
  7813. };
  7814. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7815. if (rootUrl === void 0) { rootUrl = null; }
  7816. var destination = creationFunction();
  7817. if (!rootUrl) {
  7818. rootUrl = "";
  7819. }
  7820. // Tags
  7821. if (BABYLON.Tags) {
  7822. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7823. }
  7824. var classStore = getMergedStore(destination);
  7825. // Properties
  7826. for (var property in classStore) {
  7827. var propertyDescriptor = classStore[property];
  7828. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7829. var propertyType = propertyDescriptor.type;
  7830. if (sourceProperty !== undefined && sourceProperty !== null) {
  7831. var dest = destination;
  7832. switch (propertyType) {
  7833. case 0:// Value
  7834. dest[property] = sourceProperty;
  7835. break;
  7836. case 1:// Texture
  7837. if (scene) {
  7838. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7839. }
  7840. break;
  7841. case 2:// Color3
  7842. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7843. break;
  7844. case 3:// FresnelParameters
  7845. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7846. break;
  7847. case 4:// Vector2
  7848. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7849. break;
  7850. case 5:// Vector3
  7851. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7852. break;
  7853. case 6:// Mesh reference
  7854. if (scene) {
  7855. dest[property] = scene.getLastMeshByID(sourceProperty);
  7856. }
  7857. break;
  7858. case 7:// Color Curves
  7859. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7860. break;
  7861. case 8:// Color 4
  7862. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7863. break;
  7864. case 9:// Image Processing
  7865. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7866. break;
  7867. case 10:// Quaternion
  7868. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7869. break;
  7870. case 11:// Camera reference
  7871. if (scene) {
  7872. dest[property] = scene.getCameraByID(sourceProperty);
  7873. }
  7874. break;
  7875. }
  7876. }
  7877. }
  7878. return destination;
  7879. };
  7880. SerializationHelper.Clone = function (creationFunction, source) {
  7881. return _copySource(creationFunction, source, false);
  7882. };
  7883. SerializationHelper.Instanciate = function (creationFunction, source) {
  7884. return _copySource(creationFunction, source, true);
  7885. };
  7886. return SerializationHelper;
  7887. }());
  7888. BABYLON.SerializationHelper = SerializationHelper;
  7889. })(BABYLON || (BABYLON = {}));
  7890. //# sourceMappingURL=babylon.decorators.js.map
  7891. "use strict";
  7892. var BABYLON;
  7893. (function (BABYLON) {
  7894. /**
  7895. * Wrapper class for promise with external resolve and reject.
  7896. */
  7897. var Deferred = /** @class */ (function () {
  7898. /**
  7899. * Constructor for this deferred object.
  7900. */
  7901. function Deferred() {
  7902. var _this = this;
  7903. this.promise = new Promise(function (resolve, reject) {
  7904. _this._resolve = resolve;
  7905. _this._reject = reject;
  7906. });
  7907. }
  7908. Object.defineProperty(Deferred.prototype, "resolve", {
  7909. /**
  7910. * The resolve method of the promise associated with this deferred object.
  7911. */
  7912. get: function () {
  7913. return this._resolve;
  7914. },
  7915. enumerable: true,
  7916. configurable: true
  7917. });
  7918. Object.defineProperty(Deferred.prototype, "reject", {
  7919. /**
  7920. * The reject method of the promise associated with this deferred object.
  7921. */
  7922. get: function () {
  7923. return this._reject;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. return Deferred;
  7929. }());
  7930. BABYLON.Deferred = Deferred;
  7931. })(BABYLON || (BABYLON = {}));
  7932. //# sourceMappingURL=babylon.deferred.js.map
  7933. "use strict";
  7934. var BABYLON;
  7935. (function (BABYLON) {
  7936. /**
  7937. * A class serves as a medium between the observable and its observers
  7938. */
  7939. var EventState = /** @class */ (function () {
  7940. /**
  7941. * Create a new EventState
  7942. * @param mask defines the mask associated with this state
  7943. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7944. * @param target defines the original target of the state
  7945. * @param currentTarget defines the current target of the state
  7946. */
  7947. function EventState(mask, skipNextObservers, target, currentTarget) {
  7948. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7949. this.initalize(mask, skipNextObservers, target, currentTarget);
  7950. }
  7951. /**
  7952. * Initialize the current event state
  7953. * @param mask defines the mask associated with this state
  7954. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7955. * @param target defines the original target of the state
  7956. * @param currentTarget defines the current target of the state
  7957. * @returns the current event state
  7958. */
  7959. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7960. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7961. this.mask = mask;
  7962. this.skipNextObservers = skipNextObservers;
  7963. this.target = target;
  7964. this.currentTarget = currentTarget;
  7965. return this;
  7966. };
  7967. return EventState;
  7968. }());
  7969. BABYLON.EventState = EventState;
  7970. /**
  7971. * Represent an Observer registered to a given Observable object.
  7972. */
  7973. var Observer = /** @class */ (function () {
  7974. /**
  7975. * Creates a new observer
  7976. * @param callback defines the callback to call when the observer is notified
  7977. * @param mask defines the mask of the observer (used to filter notifications)
  7978. * @param scope defines the current scope used to restore the JS context
  7979. */
  7980. function Observer(
  7981. /**
  7982. * Defines the callback to call when the observer is notified
  7983. */
  7984. callback,
  7985. /**
  7986. * Defines the mask of the observer (used to filter notifications)
  7987. */
  7988. mask,
  7989. /**
  7990. * Defines the current scope used to restore the JS context
  7991. */
  7992. scope) {
  7993. if (scope === void 0) { scope = null; }
  7994. this.callback = callback;
  7995. this.mask = mask;
  7996. this.scope = scope;
  7997. /** @ignore */
  7998. this._willBeUnregistered = false;
  7999. /**
  8000. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8001. */
  8002. this.unregisterOnNextCall = false;
  8003. }
  8004. return Observer;
  8005. }());
  8006. BABYLON.Observer = Observer;
  8007. /**
  8008. * Represent a list of observers registered to multiple Observables object.
  8009. */
  8010. var MultiObserver = /** @class */ (function () {
  8011. function MultiObserver() {
  8012. }
  8013. /**
  8014. * Release associated resources
  8015. */
  8016. MultiObserver.prototype.dispose = function () {
  8017. if (this._observers && this._observables) {
  8018. for (var index = 0; index < this._observers.length; index++) {
  8019. this._observables[index].remove(this._observers[index]);
  8020. }
  8021. }
  8022. this._observers = null;
  8023. this._observables = null;
  8024. };
  8025. /**
  8026. * Raise a callback when one of the observable will notify
  8027. * @param observables defines a list of observables to watch
  8028. * @param callback defines the callback to call on notification
  8029. * @param mask defines the mask used to filter notifications
  8030. * @param scope defines the current scope used to restore the JS context
  8031. * @returns the new MultiObserver
  8032. */
  8033. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8034. if (mask === void 0) { mask = -1; }
  8035. if (scope === void 0) { scope = null; }
  8036. var result = new MultiObserver();
  8037. result._observers = new Array();
  8038. result._observables = observables;
  8039. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8040. var observable = observables_1[_i];
  8041. var observer = observable.add(callback, mask, false, scope);
  8042. if (observer) {
  8043. result._observers.push(observer);
  8044. }
  8045. }
  8046. return result;
  8047. };
  8048. return MultiObserver;
  8049. }());
  8050. BABYLON.MultiObserver = MultiObserver;
  8051. /**
  8052. * The Observable class is a simple implementation of the Observable pattern.
  8053. *
  8054. * 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.
  8055. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8056. * 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).
  8057. * 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.
  8058. */
  8059. var Observable = /** @class */ (function () {
  8060. /**
  8061. * Creates a new observable
  8062. * @param onObserverAdded defines a callback to call when a new observer is added
  8063. */
  8064. function Observable(onObserverAdded) {
  8065. this._observers = new Array();
  8066. this._eventState = new EventState(0);
  8067. if (onObserverAdded) {
  8068. this._onObserverAdded = onObserverAdded;
  8069. }
  8070. }
  8071. /**
  8072. * Create a new Observer with the specified callback
  8073. * @param callback the callback that will be executed for that Observer
  8074. * @param mask the mask used to filter observers
  8075. * @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.
  8076. * @param scope optional scope for the callback to be called from
  8077. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8078. * @returns the new observer created for the callback
  8079. */
  8080. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8081. if (mask === void 0) { mask = -1; }
  8082. if (insertFirst === void 0) { insertFirst = false; }
  8083. if (scope === void 0) { scope = null; }
  8084. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8085. if (!callback) {
  8086. return null;
  8087. }
  8088. var observer = new Observer(callback, mask, scope);
  8089. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8090. if (insertFirst) {
  8091. this._observers.unshift(observer);
  8092. }
  8093. else {
  8094. this._observers.push(observer);
  8095. }
  8096. if (this._onObserverAdded) {
  8097. this._onObserverAdded(observer);
  8098. }
  8099. return observer;
  8100. };
  8101. /**
  8102. * Remove an Observer from the Observable object
  8103. * @param observer the instance of the Observer to remove
  8104. * @returns false if it doesn't belong to this Observable
  8105. */
  8106. Observable.prototype.remove = function (observer) {
  8107. if (!observer) {
  8108. return false;
  8109. }
  8110. var index = this._observers.indexOf(observer);
  8111. if (index !== -1) {
  8112. this._observers.splice(index, 1);
  8113. return true;
  8114. }
  8115. return false;
  8116. };
  8117. /**
  8118. * Remove a callback from the Observable object
  8119. * @param callback the callback to remove
  8120. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8121. * @returns false if it doesn't belong to this Observable
  8122. */
  8123. Observable.prototype.removeCallback = function (callback, scope) {
  8124. for (var index = 0; index < this._observers.length; index++) {
  8125. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8126. this._observers.splice(index, 1);
  8127. return true;
  8128. }
  8129. }
  8130. return false;
  8131. };
  8132. Observable.prototype._deferUnregister = function (observer) {
  8133. var _this = this;
  8134. observer.unregisterOnNextCall = false;
  8135. observer._willBeUnregistered = true;
  8136. BABYLON.Tools.SetImmediate(function () {
  8137. _this.remove(observer);
  8138. });
  8139. };
  8140. /**
  8141. * Notify all Observers by calling their respective callback with the given data
  8142. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8143. * @param eventData defines the data to send to all observers
  8144. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8145. * @param target defines the original target of the state
  8146. * @param currentTarget defines the current target of the state
  8147. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8148. */
  8149. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8150. if (mask === void 0) { mask = -1; }
  8151. if (!this._observers.length) {
  8152. return true;
  8153. }
  8154. var state = this._eventState;
  8155. state.mask = mask;
  8156. state.target = target;
  8157. state.currentTarget = currentTarget;
  8158. state.skipNextObservers = false;
  8159. state.lastReturnValue = eventData;
  8160. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8161. var obs = _a[_i];
  8162. if (obs._willBeUnregistered) {
  8163. continue;
  8164. }
  8165. if (obs.mask & mask) {
  8166. if (obs.scope) {
  8167. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8168. }
  8169. else {
  8170. state.lastReturnValue = obs.callback(eventData, state);
  8171. }
  8172. if (obs.unregisterOnNextCall) {
  8173. this._deferUnregister(obs);
  8174. }
  8175. }
  8176. if (state.skipNextObservers) {
  8177. return false;
  8178. }
  8179. }
  8180. return true;
  8181. };
  8182. /**
  8183. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8184. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8185. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8186. * and it is crucial that all callbacks will be executed.
  8187. * The order of the callbacks is kept, callbacks are not executed parallel.
  8188. *
  8189. * @param eventData The data to be sent to each callback
  8190. * @param mask is used to filter observers defaults to -1
  8191. * @param target defines the callback target (see EventState)
  8192. * @param currentTarget defines he current object in the bubbling phase
  8193. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8194. */
  8195. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8196. var _this = this;
  8197. if (mask === void 0) { mask = -1; }
  8198. // create an empty promise
  8199. var p = Promise.resolve(eventData);
  8200. // no observers? return this promise.
  8201. if (!this._observers.length) {
  8202. return p;
  8203. }
  8204. var state = this._eventState;
  8205. state.mask = mask;
  8206. state.target = target;
  8207. state.currentTarget = currentTarget;
  8208. state.skipNextObservers = false;
  8209. // execute one callback after another (not using Promise.all, the order is important)
  8210. this._observers.forEach(function (obs) {
  8211. if (state.skipNextObservers) {
  8212. return;
  8213. }
  8214. if (obs._willBeUnregistered) {
  8215. return;
  8216. }
  8217. if (obs.mask & mask) {
  8218. if (obs.scope) {
  8219. p = p.then(function (lastReturnedValue) {
  8220. state.lastReturnValue = lastReturnedValue;
  8221. return obs.callback.apply(obs.scope, [eventData, state]);
  8222. });
  8223. }
  8224. else {
  8225. p = p.then(function (lastReturnedValue) {
  8226. state.lastReturnValue = lastReturnedValue;
  8227. return obs.callback(eventData, state);
  8228. });
  8229. }
  8230. if (obs.unregisterOnNextCall) {
  8231. _this._deferUnregister(obs);
  8232. }
  8233. }
  8234. });
  8235. // return the eventData
  8236. return p.then(function () { return eventData; });
  8237. };
  8238. /**
  8239. * Notify a specific observer
  8240. * @param observer defines the observer to notify
  8241. * @param eventData defines the data to be sent to each callback
  8242. * @param mask is used to filter observers defaults to -1
  8243. */
  8244. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8245. if (mask === void 0) { mask = -1; }
  8246. var state = this._eventState;
  8247. state.mask = mask;
  8248. state.skipNextObservers = false;
  8249. observer.callback(eventData, state);
  8250. };
  8251. /**
  8252. * Gets a boolean indicating if the observable has at least one observer
  8253. * @returns true is the Observable has at least one Observer registered
  8254. */
  8255. Observable.prototype.hasObservers = function () {
  8256. return this._observers.length > 0;
  8257. };
  8258. /**
  8259. * Clear the list of observers
  8260. */
  8261. Observable.prototype.clear = function () {
  8262. this._observers = new Array();
  8263. this._onObserverAdded = null;
  8264. };
  8265. /**
  8266. * Clone the current observable
  8267. * @returns a new observable
  8268. */
  8269. Observable.prototype.clone = function () {
  8270. var result = new Observable();
  8271. result._observers = this._observers.slice(0);
  8272. return result;
  8273. };
  8274. /**
  8275. * Does this observable handles observer registered with a given mask
  8276. * @param mask defines the mask to be tested
  8277. * @return whether or not one observer registered with the given mask is handeled
  8278. **/
  8279. Observable.prototype.hasSpecificMask = function (mask) {
  8280. if (mask === void 0) { mask = -1; }
  8281. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8282. var obs = _a[_i];
  8283. if (obs.mask & mask || obs.mask === mask) {
  8284. return true;
  8285. }
  8286. }
  8287. return false;
  8288. };
  8289. return Observable;
  8290. }());
  8291. BABYLON.Observable = Observable;
  8292. })(BABYLON || (BABYLON = {}));
  8293. //# sourceMappingURL=babylon.observable.js.map
  8294. "use strict";
  8295. var BABYLON;
  8296. (function (BABYLON) {
  8297. var SmartArray = /** @class */ (function () {
  8298. function SmartArray(capacity) {
  8299. this.length = 0;
  8300. this.data = new Array(capacity);
  8301. this._id = SmartArray._GlobalId++;
  8302. }
  8303. SmartArray.prototype.push = function (value) {
  8304. this.data[this.length++] = value;
  8305. if (this.length > this.data.length) {
  8306. this.data.length *= 2;
  8307. }
  8308. };
  8309. SmartArray.prototype.forEach = function (func) {
  8310. for (var index = 0; index < this.length; index++) {
  8311. func(this.data[index]);
  8312. }
  8313. };
  8314. SmartArray.prototype.sort = function (compareFn) {
  8315. this.data.sort(compareFn);
  8316. };
  8317. SmartArray.prototype.reset = function () {
  8318. this.length = 0;
  8319. };
  8320. SmartArray.prototype.dispose = function () {
  8321. this.reset();
  8322. if (this.data) {
  8323. this.data.length = 0;
  8324. this.data = [];
  8325. }
  8326. };
  8327. SmartArray.prototype.concat = function (array) {
  8328. if (array.length === 0) {
  8329. return;
  8330. }
  8331. if (this.length + array.length > this.data.length) {
  8332. this.data.length = (this.length + array.length) * 2;
  8333. }
  8334. for (var index = 0; index < array.length; index++) {
  8335. this.data[this.length++] = (array.data || array)[index];
  8336. }
  8337. };
  8338. SmartArray.prototype.indexOf = function (value) {
  8339. var position = this.data.indexOf(value);
  8340. if (position >= this.length) {
  8341. return -1;
  8342. }
  8343. return position;
  8344. };
  8345. SmartArray.prototype.contains = function (value) {
  8346. return this.data.indexOf(value) !== -1;
  8347. };
  8348. // Statics
  8349. SmartArray._GlobalId = 0;
  8350. return SmartArray;
  8351. }());
  8352. BABYLON.SmartArray = SmartArray;
  8353. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8354. __extends(SmartArrayNoDuplicate, _super);
  8355. function SmartArrayNoDuplicate() {
  8356. var _this = _super !== null && _super.apply(this, arguments) || this;
  8357. _this._duplicateId = 0;
  8358. return _this;
  8359. }
  8360. SmartArrayNoDuplicate.prototype.push = function (value) {
  8361. _super.prototype.push.call(this, value);
  8362. if (!value.__smartArrayFlags) {
  8363. value.__smartArrayFlags = {};
  8364. }
  8365. value.__smartArrayFlags[this._id] = this._duplicateId;
  8366. };
  8367. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8368. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8369. return false;
  8370. }
  8371. this.push(value);
  8372. return true;
  8373. };
  8374. SmartArrayNoDuplicate.prototype.reset = function () {
  8375. _super.prototype.reset.call(this);
  8376. this._duplicateId++;
  8377. };
  8378. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8379. if (array.length === 0) {
  8380. return;
  8381. }
  8382. if (this.length + array.length > this.data.length) {
  8383. this.data.length = (this.length + array.length) * 2;
  8384. }
  8385. for (var index = 0; index < array.length; index++) {
  8386. var item = (array.data || array)[index];
  8387. this.pushNoDuplicate(item);
  8388. }
  8389. };
  8390. return SmartArrayNoDuplicate;
  8391. }(SmartArray));
  8392. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8393. })(BABYLON || (BABYLON = {}));
  8394. //# sourceMappingURL=babylon.smartArray.js.map
  8395. "use strict";
  8396. var BABYLON;
  8397. (function (BABYLON) {
  8398. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8399. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8400. var LoadFileError = /** @class */ (function (_super) {
  8401. __extends(LoadFileError, _super);
  8402. function LoadFileError(message, request) {
  8403. var _this = _super.call(this, message) || this;
  8404. _this.request = request;
  8405. _this.name = "LoadFileError";
  8406. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8407. return _this;
  8408. }
  8409. // Polyfill for Object.setPrototypeOf if necessary.
  8410. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8411. return LoadFileError;
  8412. }(Error));
  8413. BABYLON.LoadFileError = LoadFileError;
  8414. var RetryStrategy = /** @class */ (function () {
  8415. function RetryStrategy() {
  8416. }
  8417. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8418. if (maxRetries === void 0) { maxRetries = 3; }
  8419. if (baseInterval === void 0) { baseInterval = 500; }
  8420. return function (url, request, retryIndex) {
  8421. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8422. return -1;
  8423. }
  8424. return Math.pow(2, retryIndex) * baseInterval;
  8425. };
  8426. };
  8427. return RetryStrategy;
  8428. }());
  8429. BABYLON.RetryStrategy = RetryStrategy;
  8430. // Screenshots
  8431. var screenshotCanvas;
  8432. var cloneValue = function (source, destinationObject) {
  8433. if (!source)
  8434. return null;
  8435. if (source instanceof BABYLON.Mesh) {
  8436. return null;
  8437. }
  8438. if (source instanceof BABYLON.SubMesh) {
  8439. return source.clone(destinationObject);
  8440. }
  8441. else if (source.clone) {
  8442. return source.clone();
  8443. }
  8444. return null;
  8445. };
  8446. var Tools = /** @class */ (function () {
  8447. function Tools() {
  8448. }
  8449. /**
  8450. * Interpolates between a and b via alpha
  8451. * @param a The lower value (returned when alpha = 0)
  8452. * @param b The upper value (returned when alpha = 1)
  8453. * @param alpha The interpolation-factor
  8454. * @return The mixed value
  8455. */
  8456. Tools.Mix = function (a, b, alpha) {
  8457. return a * (1 - alpha) + b * alpha;
  8458. };
  8459. Tools.Instantiate = function (className) {
  8460. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8461. return Tools.RegisteredExternalClasses[className];
  8462. }
  8463. var arr = className.split(".");
  8464. var fn = (window || this);
  8465. for (var i = 0, len = arr.length; i < len; i++) {
  8466. fn = fn[arr[i]];
  8467. }
  8468. if (typeof fn !== "function") {
  8469. return null;
  8470. }
  8471. return fn;
  8472. };
  8473. /**
  8474. * Provides a slice function that will work even on IE
  8475. * @param data defines the array to slice
  8476. * @param start defines the start of the data (optional)
  8477. * @param end defines the end of the data (optional)
  8478. * @returns the new sliced array
  8479. */
  8480. Tools.Slice = function (data, start, end) {
  8481. if (data.slice) {
  8482. return data.slice(start, end);
  8483. }
  8484. return Array.prototype.slice.call(data, start, end);
  8485. };
  8486. Tools.SetImmediate = function (action) {
  8487. if (window.setImmediate) {
  8488. window.setImmediate(action);
  8489. }
  8490. else {
  8491. setTimeout(action, 1);
  8492. }
  8493. };
  8494. Tools.IsExponentOfTwo = function (value) {
  8495. var count = 1;
  8496. do {
  8497. count *= 2;
  8498. } while (count < value);
  8499. return count === value;
  8500. };
  8501. /**
  8502. * Find the next highest power of two.
  8503. * @param x Number to start search from.
  8504. * @return Next highest power of two.
  8505. */
  8506. Tools.CeilingPOT = function (x) {
  8507. x--;
  8508. x |= x >> 1;
  8509. x |= x >> 2;
  8510. x |= x >> 4;
  8511. x |= x >> 8;
  8512. x |= x >> 16;
  8513. x++;
  8514. return x;
  8515. };
  8516. /**
  8517. * Find the next lowest power of two.
  8518. * @param x Number to start search from.
  8519. * @return Next lowest power of two.
  8520. */
  8521. Tools.FloorPOT = function (x) {
  8522. x = x | (x >> 1);
  8523. x = x | (x >> 2);
  8524. x = x | (x >> 4);
  8525. x = x | (x >> 8);
  8526. x = x | (x >> 16);
  8527. return x - (x >> 1);
  8528. };
  8529. /**
  8530. * Find the nearest power of two.
  8531. * @param x Number to start search from.
  8532. * @return Next nearest power of two.
  8533. */
  8534. Tools.NearestPOT = function (x) {
  8535. var c = Tools.CeilingPOT(x);
  8536. var f = Tools.FloorPOT(x);
  8537. return (c - x) > (x - f) ? f : c;
  8538. };
  8539. Tools.GetExponentOfTwo = function (value, max, mode) {
  8540. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8541. var pot;
  8542. switch (mode) {
  8543. case BABYLON.Engine.SCALEMODE_FLOOR:
  8544. pot = Tools.FloorPOT(value);
  8545. break;
  8546. case BABYLON.Engine.SCALEMODE_NEAREST:
  8547. pot = Tools.NearestPOT(value);
  8548. break;
  8549. case BABYLON.Engine.SCALEMODE_CEILING:
  8550. default:
  8551. pot = Tools.CeilingPOT(value);
  8552. break;
  8553. }
  8554. return Math.min(pot, max);
  8555. };
  8556. Tools.GetFilename = function (path) {
  8557. var index = path.lastIndexOf("/");
  8558. if (index < 0)
  8559. return path;
  8560. return path.substring(index + 1);
  8561. };
  8562. /**
  8563. * Extracts the "folder" part of a path (everything before the filename).
  8564. * @param uri The URI to extract the info from
  8565. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8566. * @returns The "folder" part of the path
  8567. */
  8568. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8569. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8570. var index = uri.lastIndexOf("/");
  8571. if (index < 0) {
  8572. if (returnUnchangedIfNoSlash) {
  8573. return uri;
  8574. }
  8575. return "";
  8576. }
  8577. return uri.substring(0, index + 1);
  8578. };
  8579. Tools.GetDOMTextContent = function (element) {
  8580. var result = "";
  8581. var child = element.firstChild;
  8582. while (child) {
  8583. if (child.nodeType === 3) {
  8584. result += child.textContent;
  8585. }
  8586. child = child.nextSibling;
  8587. }
  8588. return result;
  8589. };
  8590. Tools.ToDegrees = function (angle) {
  8591. return angle * 180 / Math.PI;
  8592. };
  8593. Tools.ToRadians = function (angle) {
  8594. return angle * Math.PI / 180;
  8595. };
  8596. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8597. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8598. var output = "";
  8599. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8600. var i = 0;
  8601. var bytes = new Uint8Array(buffer);
  8602. while (i < bytes.length) {
  8603. chr1 = bytes[i++];
  8604. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8605. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8606. enc1 = chr1 >> 2;
  8607. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8608. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8609. enc4 = chr3 & 63;
  8610. if (isNaN(chr2)) {
  8611. enc3 = enc4 = 64;
  8612. }
  8613. else if (isNaN(chr3)) {
  8614. enc4 = 64;
  8615. }
  8616. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8617. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8618. }
  8619. return "data:image/png;base64," + output;
  8620. };
  8621. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8622. if (bias === void 0) { bias = null; }
  8623. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8624. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8625. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8626. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8627. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8628. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8629. }
  8630. if (bias) {
  8631. minimum.x -= minimum.x * bias.x + bias.y;
  8632. minimum.y -= minimum.y * bias.x + bias.y;
  8633. minimum.z -= minimum.z * bias.x + bias.y;
  8634. maximum.x += maximum.x * bias.x + bias.y;
  8635. maximum.y += maximum.y * bias.x + bias.y;
  8636. maximum.z += maximum.z * bias.x + bias.y;
  8637. }
  8638. return {
  8639. minimum: minimum,
  8640. maximum: maximum
  8641. };
  8642. };
  8643. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8644. if (bias === void 0) { bias = null; }
  8645. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8646. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8647. if (!stride) {
  8648. stride = 3;
  8649. }
  8650. for (var index = start; index < start + count; index++) {
  8651. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8652. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8653. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8654. }
  8655. if (bias) {
  8656. minimum.x -= minimum.x * bias.x + bias.y;
  8657. minimum.y -= minimum.y * bias.x + bias.y;
  8658. minimum.z -= minimum.z * bias.x + bias.y;
  8659. maximum.x += maximum.x * bias.x + bias.y;
  8660. maximum.y += maximum.y * bias.x + bias.y;
  8661. maximum.z += maximum.z * bias.x + bias.y;
  8662. }
  8663. return {
  8664. minimum: minimum,
  8665. maximum: maximum
  8666. };
  8667. };
  8668. Tools.Vector2ArrayFeeder = function (array) {
  8669. return function (index) {
  8670. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8671. var length = isFloatArray ? array.length / 2 : array.length;
  8672. if (index >= length) {
  8673. return null;
  8674. }
  8675. if (isFloatArray) {
  8676. var fa = array;
  8677. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8678. }
  8679. var a = array;
  8680. return a[index];
  8681. };
  8682. };
  8683. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8684. if (bias === void 0) { bias = null; }
  8685. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8686. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8687. var i = 0;
  8688. var cur = feeder(i++);
  8689. while (cur) {
  8690. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8691. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8692. cur = feeder(i++);
  8693. }
  8694. if (bias) {
  8695. minimum.x -= minimum.x * bias.x + bias.y;
  8696. minimum.y -= minimum.y * bias.x + bias.y;
  8697. maximum.x += maximum.x * bias.x + bias.y;
  8698. maximum.y += maximum.y * bias.x + bias.y;
  8699. }
  8700. return {
  8701. minimum: minimum,
  8702. maximum: maximum
  8703. };
  8704. };
  8705. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8706. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8707. return null;
  8708. return Array.isArray(obj) ? obj : [obj];
  8709. };
  8710. // Misc.
  8711. Tools.GetPointerPrefix = function () {
  8712. var eventPrefix = "pointer";
  8713. // Check if pointer events are supported
  8714. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8715. eventPrefix = "mouse";
  8716. }
  8717. return eventPrefix;
  8718. };
  8719. /**
  8720. * @param func - the function to be called
  8721. * @param requester - the object that will request the next frame. Falls back to window.
  8722. */
  8723. Tools.QueueNewFrame = function (func, requester) {
  8724. if (!Tools.IsWindowObjectExist()) {
  8725. return setTimeout(func, 16);
  8726. }
  8727. if (!requester) {
  8728. requester = window;
  8729. }
  8730. if (requester.requestAnimationFrame) {
  8731. return requester.requestAnimationFrame(func);
  8732. }
  8733. else if (requester.msRequestAnimationFrame) {
  8734. return requester.msRequestAnimationFrame(func);
  8735. }
  8736. else if (requester.webkitRequestAnimationFrame) {
  8737. return requester.webkitRequestAnimationFrame(func);
  8738. }
  8739. else if (requester.mozRequestAnimationFrame) {
  8740. return requester.mozRequestAnimationFrame(func);
  8741. }
  8742. else if (requester.oRequestAnimationFrame) {
  8743. return requester.oRequestAnimationFrame(func);
  8744. }
  8745. else {
  8746. return window.setTimeout(func, 16);
  8747. }
  8748. };
  8749. Tools.RequestFullscreen = function (element) {
  8750. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8751. if (!requestFunction)
  8752. return;
  8753. requestFunction.call(element);
  8754. };
  8755. Tools.ExitFullscreen = function () {
  8756. if (document.exitFullscreen) {
  8757. document.exitFullscreen();
  8758. }
  8759. else if (document.mozCancelFullScreen) {
  8760. document.mozCancelFullScreen();
  8761. }
  8762. else if (document.webkitCancelFullScreen) {
  8763. document.webkitCancelFullScreen();
  8764. }
  8765. else if (document.msCancelFullScreen) {
  8766. document.msCancelFullScreen();
  8767. }
  8768. };
  8769. Tools.SetCorsBehavior = function (url, element) {
  8770. if (url && url.indexOf("data:") === 0) {
  8771. return;
  8772. }
  8773. if (Tools.CorsBehavior) {
  8774. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8775. element.crossOrigin = Tools.CorsBehavior;
  8776. }
  8777. else {
  8778. var result = Tools.CorsBehavior(url);
  8779. if (result) {
  8780. element.crossOrigin = result;
  8781. }
  8782. }
  8783. }
  8784. };
  8785. // External files
  8786. Tools.CleanUrl = function (url) {
  8787. url = url.replace(/#/mg, "%23");
  8788. return url;
  8789. };
  8790. Tools.LoadImage = function (url, onLoad, onError, database) {
  8791. if (url instanceof ArrayBuffer) {
  8792. url = Tools.EncodeArrayBufferTobase64(url);
  8793. }
  8794. url = Tools.CleanUrl(url);
  8795. url = Tools.PreprocessUrl(url);
  8796. var img = new Image();
  8797. Tools.SetCorsBehavior(url, img);
  8798. var loadHandler = function () {
  8799. img.removeEventListener("load", loadHandler);
  8800. img.removeEventListener("error", errorHandler);
  8801. onLoad(img);
  8802. };
  8803. var errorHandler = function (err) {
  8804. img.removeEventListener("load", loadHandler);
  8805. img.removeEventListener("error", errorHandler);
  8806. Tools.Error("Error while trying to load image: " + url);
  8807. if (onError) {
  8808. onError("Error while trying to load image: " + url, err);
  8809. }
  8810. };
  8811. img.addEventListener("load", loadHandler);
  8812. img.addEventListener("error", errorHandler);
  8813. var noIndexedDB = function () {
  8814. img.src = url;
  8815. };
  8816. var loadFromIndexedDB = function () {
  8817. if (database) {
  8818. database.loadImageFromDB(url, img);
  8819. }
  8820. };
  8821. //ANY database to do!
  8822. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8823. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8824. }
  8825. else {
  8826. if (url.indexOf("file:") !== -1) {
  8827. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8828. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8829. try {
  8830. var blobURL;
  8831. try {
  8832. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8833. }
  8834. catch (ex) {
  8835. // Chrome doesn't support oneTimeOnly parameter
  8836. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8837. }
  8838. img.src = blobURL;
  8839. }
  8840. catch (e) {
  8841. img.src = "";
  8842. }
  8843. return img;
  8844. }
  8845. }
  8846. noIndexedDB();
  8847. }
  8848. return img;
  8849. };
  8850. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8851. url = Tools.CleanUrl(url);
  8852. url = Tools.PreprocessUrl(url);
  8853. // If file and file input are set
  8854. if (url.indexOf("file:") !== -1) {
  8855. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8856. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8857. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8858. }
  8859. }
  8860. var loadUrl = Tools.BaseUrl + url;
  8861. var aborted = false;
  8862. var fileRequest = {
  8863. onCompleteObservable: new BABYLON.Observable(),
  8864. abort: function () { return aborted = true; },
  8865. };
  8866. var requestFile = function () {
  8867. var request = new XMLHttpRequest();
  8868. var retryHandle = null;
  8869. fileRequest.abort = function () {
  8870. aborted = true;
  8871. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8872. request.abort();
  8873. }
  8874. if (retryHandle !== null) {
  8875. clearTimeout(retryHandle);
  8876. retryHandle = null;
  8877. }
  8878. };
  8879. var retryLoop = function (retryIndex) {
  8880. request.open('GET', loadUrl, true);
  8881. if (useArrayBuffer) {
  8882. request.responseType = "arraybuffer";
  8883. }
  8884. if (onProgress) {
  8885. request.addEventListener("progress", onProgress);
  8886. }
  8887. var onLoadEnd = function () {
  8888. request.removeEventListener("loadend", onLoadEnd);
  8889. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8890. fileRequest.onCompleteObservable.clear();
  8891. };
  8892. request.addEventListener("loadend", onLoadEnd);
  8893. var onReadyStateChange = function () {
  8894. if (aborted) {
  8895. return;
  8896. }
  8897. // In case of undefined state in some browsers.
  8898. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8899. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8900. request.removeEventListener("readystatechange", onReadyStateChange);
  8901. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8902. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8903. return;
  8904. }
  8905. var retryStrategy = Tools.DefaultRetryStrategy;
  8906. if (retryStrategy) {
  8907. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8908. if (waitTime !== -1) {
  8909. // Prevent the request from completing for retry.
  8910. request.removeEventListener("loadend", onLoadEnd);
  8911. request = new XMLHttpRequest();
  8912. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8913. return;
  8914. }
  8915. }
  8916. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8917. if (onError) {
  8918. onError(request, e);
  8919. }
  8920. else {
  8921. throw e;
  8922. }
  8923. }
  8924. };
  8925. request.addEventListener("readystatechange", onReadyStateChange);
  8926. request.send();
  8927. };
  8928. retryLoop(0);
  8929. };
  8930. // Caching all files
  8931. if (database && database.enableSceneOffline) {
  8932. var noIndexedDB_1 = function () {
  8933. if (!aborted) {
  8934. requestFile();
  8935. }
  8936. };
  8937. var loadFromIndexedDB = function () {
  8938. // TODO: database needs to support aborting and should return a IFileRequest
  8939. if (aborted) {
  8940. return;
  8941. }
  8942. if (database) {
  8943. database.loadFileFromDB(url, function (data) {
  8944. if (!aborted) {
  8945. onSuccess(data);
  8946. }
  8947. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8948. }, onProgress ? function (event) {
  8949. if (!aborted) {
  8950. onProgress(event);
  8951. }
  8952. } : undefined, noIndexedDB_1, useArrayBuffer);
  8953. }
  8954. };
  8955. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8956. }
  8957. else {
  8958. requestFile();
  8959. }
  8960. return fileRequest;
  8961. };
  8962. /**
  8963. * Load a script (identified by an url). When the url returns, the
  8964. * content of this file is added into a new script element, attached to the DOM (body element)
  8965. */
  8966. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8967. var head = document.getElementsByTagName('head')[0];
  8968. var script = document.createElement('script');
  8969. script.type = 'text/javascript';
  8970. script.src = scriptUrl;
  8971. script.onload = function () {
  8972. if (onSuccess) {
  8973. onSuccess();
  8974. }
  8975. };
  8976. script.onerror = function (e) {
  8977. if (onError) {
  8978. onError("Unable to load script '" + scriptUrl + "'", e);
  8979. }
  8980. };
  8981. head.appendChild(script);
  8982. };
  8983. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8984. var reader = new FileReader();
  8985. var request = {
  8986. onCompleteObservable: new BABYLON.Observable(),
  8987. abort: function () { return reader.abort(); },
  8988. };
  8989. reader.onloadend = function (e) {
  8990. request.onCompleteObservable.notifyObservers(request);
  8991. };
  8992. reader.onload = function (e) {
  8993. //target doesn't have result from ts 1.3
  8994. callback(e.target['result']);
  8995. };
  8996. reader.onprogress = progressCallback;
  8997. reader.readAsDataURL(fileToLoad);
  8998. return request;
  8999. };
  9000. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9001. var reader = new FileReader();
  9002. var request = {
  9003. onCompleteObservable: new BABYLON.Observable(),
  9004. abort: function () { return reader.abort(); },
  9005. };
  9006. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9007. reader.onerror = function (e) {
  9008. Tools.Log("Error while reading file: " + fileToLoad.name);
  9009. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9010. };
  9011. reader.onload = function (e) {
  9012. //target doesn't have result from ts 1.3
  9013. callback(e.target['result']);
  9014. };
  9015. if (progressCallBack) {
  9016. reader.onprogress = progressCallBack;
  9017. }
  9018. if (!useArrayBuffer) {
  9019. // Asynchronous read
  9020. reader.readAsText(fileToLoad);
  9021. }
  9022. else {
  9023. reader.readAsArrayBuffer(fileToLoad);
  9024. }
  9025. return request;
  9026. };
  9027. //returns a downloadable url to a file content.
  9028. Tools.FileAsURL = function (content) {
  9029. var fileBlob = new Blob([content]);
  9030. var url = window.URL || window.webkitURL;
  9031. var link = url.createObjectURL(fileBlob);
  9032. return link;
  9033. };
  9034. // Misc.
  9035. Tools.Format = function (value, decimals) {
  9036. if (decimals === void 0) { decimals = 2; }
  9037. return value.toFixed(decimals);
  9038. };
  9039. Tools.CheckExtends = function (v, min, max) {
  9040. if (v.x < min.x)
  9041. min.x = v.x;
  9042. if (v.y < min.y)
  9043. min.y = v.y;
  9044. if (v.z < min.z)
  9045. min.z = v.z;
  9046. if (v.x > max.x)
  9047. max.x = v.x;
  9048. if (v.y > max.y)
  9049. max.y = v.y;
  9050. if (v.z > max.z)
  9051. max.z = v.z;
  9052. };
  9053. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9054. for (var prop in source) {
  9055. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9056. continue;
  9057. }
  9058. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9059. continue;
  9060. }
  9061. var sourceValue = source[prop];
  9062. var typeOfSourceValue = typeof sourceValue;
  9063. if (typeOfSourceValue === "function") {
  9064. continue;
  9065. }
  9066. try {
  9067. if (typeOfSourceValue === "object") {
  9068. if (sourceValue instanceof Array) {
  9069. destination[prop] = [];
  9070. if (sourceValue.length > 0) {
  9071. if (typeof sourceValue[0] == "object") {
  9072. for (var index = 0; index < sourceValue.length; index++) {
  9073. var clonedValue = cloneValue(sourceValue[index], destination);
  9074. if (destination[prop].indexOf(clonedValue) === -1) {
  9075. destination[prop].push(clonedValue);
  9076. }
  9077. }
  9078. }
  9079. else {
  9080. destination[prop] = sourceValue.slice(0);
  9081. }
  9082. }
  9083. }
  9084. else {
  9085. destination[prop] = cloneValue(sourceValue, destination);
  9086. }
  9087. }
  9088. else {
  9089. destination[prop] = sourceValue;
  9090. }
  9091. }
  9092. catch (e) {
  9093. // Just ignore error (it could be because of a read-only property)
  9094. }
  9095. }
  9096. };
  9097. Tools.IsEmpty = function (obj) {
  9098. for (var i in obj) {
  9099. if (obj.hasOwnProperty(i)) {
  9100. return false;
  9101. }
  9102. }
  9103. return true;
  9104. };
  9105. Tools.RegisterTopRootEvents = function (events) {
  9106. for (var index = 0; index < events.length; index++) {
  9107. var event = events[index];
  9108. window.addEventListener(event.name, event.handler, false);
  9109. try {
  9110. if (window.parent) {
  9111. window.parent.addEventListener(event.name, event.handler, false);
  9112. }
  9113. }
  9114. catch (e) {
  9115. // Silently fails...
  9116. }
  9117. }
  9118. };
  9119. Tools.UnregisterTopRootEvents = function (events) {
  9120. for (var index = 0; index < events.length; index++) {
  9121. var event = events[index];
  9122. window.removeEventListener(event.name, event.handler);
  9123. try {
  9124. if (window.parent) {
  9125. window.parent.removeEventListener(event.name, event.handler);
  9126. }
  9127. }
  9128. catch (e) {
  9129. // Silently fails...
  9130. }
  9131. }
  9132. };
  9133. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9134. if (mimeType === void 0) { mimeType = "image/png"; }
  9135. // Read the contents of the framebuffer
  9136. var numberOfChannelsByLine = width * 4;
  9137. var halfHeight = height / 2;
  9138. //Reading datas from WebGL
  9139. var data = engine.readPixels(0, 0, width, height);
  9140. //To flip image on Y axis.
  9141. for (var i = 0; i < halfHeight; i++) {
  9142. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9143. var currentCell = j + i * numberOfChannelsByLine;
  9144. var targetLine = height - i - 1;
  9145. var targetCell = j + targetLine * numberOfChannelsByLine;
  9146. var temp = data[currentCell];
  9147. data[currentCell] = data[targetCell];
  9148. data[targetCell] = temp;
  9149. }
  9150. }
  9151. // Create a 2D canvas to store the result
  9152. if (!screenshotCanvas) {
  9153. screenshotCanvas = document.createElement('canvas');
  9154. }
  9155. screenshotCanvas.width = width;
  9156. screenshotCanvas.height = height;
  9157. var context = screenshotCanvas.getContext('2d');
  9158. if (context) {
  9159. // Copy the pixels to a 2D canvas
  9160. var imageData = context.createImageData(width, height);
  9161. var castData = (imageData.data);
  9162. castData.set(data);
  9163. context.putImageData(imageData, 0, 0);
  9164. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9165. }
  9166. };
  9167. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9168. if (mimeType === void 0) { mimeType = "image/png"; }
  9169. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9170. if (successCallback) {
  9171. successCallback(base64Image);
  9172. }
  9173. else {
  9174. // We need HTMLCanvasElement.toBlob for HD screenshots
  9175. if (!screenshotCanvas.toBlob) {
  9176. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9177. screenshotCanvas.toBlob = function (callback, type, quality) {
  9178. var _this = this;
  9179. setTimeout(function () {
  9180. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9181. for (var i = 0; i < len; i++) {
  9182. arr[i] = binStr.charCodeAt(i);
  9183. }
  9184. callback(new Blob([arr], { type: type || 'image/png' }));
  9185. });
  9186. };
  9187. }
  9188. screenshotCanvas.toBlob(function (blob) {
  9189. var url = URL.createObjectURL(blob);
  9190. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9191. if (("download" in document.createElement("a"))) {
  9192. var a = window.document.createElement("a");
  9193. a.href = url;
  9194. if (fileName) {
  9195. a.setAttribute("download", fileName);
  9196. }
  9197. else {
  9198. var date = new Date();
  9199. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9200. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9201. }
  9202. window.document.body.appendChild(a);
  9203. a.addEventListener("click", function () {
  9204. if (a.parentElement) {
  9205. a.parentElement.removeChild(a);
  9206. }
  9207. });
  9208. a.click();
  9209. }
  9210. else {
  9211. var newWindow = window.open("");
  9212. if (!newWindow)
  9213. return;
  9214. var img = newWindow.document.createElement("img");
  9215. img.onload = function () {
  9216. // no longer need to read the blob so it's revoked
  9217. URL.revokeObjectURL(url);
  9218. };
  9219. img.src = url;
  9220. newWindow.document.body.appendChild(img);
  9221. }
  9222. });
  9223. }
  9224. };
  9225. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9226. if (mimeType === void 0) { mimeType = "image/png"; }
  9227. var width;
  9228. var height;
  9229. // If a precision value is specified
  9230. if (size.precision) {
  9231. width = Math.round(engine.getRenderWidth() * size.precision);
  9232. height = Math.round(width / engine.getAspectRatio(camera));
  9233. }
  9234. else if (size.width && size.height) {
  9235. width = size.width;
  9236. height = size.height;
  9237. }
  9238. else if (size.width && !size.height) {
  9239. width = size.width;
  9240. height = Math.round(width / engine.getAspectRatio(camera));
  9241. }
  9242. else if (size.height && !size.width) {
  9243. height = size.height;
  9244. width = Math.round(height * engine.getAspectRatio(camera));
  9245. }
  9246. else if (!isNaN(size)) {
  9247. height = size;
  9248. width = size;
  9249. }
  9250. else {
  9251. Tools.Error("Invalid 'size' parameter !");
  9252. return;
  9253. }
  9254. if (!screenshotCanvas) {
  9255. screenshotCanvas = document.createElement('canvas');
  9256. }
  9257. screenshotCanvas.width = width;
  9258. screenshotCanvas.height = height;
  9259. var renderContext = screenshotCanvas.getContext("2d");
  9260. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9261. var newWidth = width;
  9262. var newHeight = newWidth / ratio;
  9263. if (newHeight > height) {
  9264. newHeight = height;
  9265. newWidth = newHeight * ratio;
  9266. }
  9267. var offsetX = Math.max(0, width - newWidth) / 2;
  9268. var offsetY = Math.max(0, height - newHeight) / 2;
  9269. var renderingCanvas = engine.getRenderingCanvas();
  9270. if (renderContext && renderingCanvas) {
  9271. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9272. }
  9273. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9274. };
  9275. /**
  9276. * Generates an image screenshot from the specified camera.
  9277. *
  9278. * @param engine The engine to use for rendering
  9279. * @param camera The camera to use for rendering
  9280. * @param size This parameter can be set to a single number or to an object with the
  9281. * following (optional) properties: precision, width, height. If a single number is passed,
  9282. * it will be used for both width and height. If an object is passed, the screenshot size
  9283. * will be derived from the parameters. The precision property is a multiplier allowing
  9284. * rendering at a higher or lower resolution.
  9285. * @param successCallback The callback receives a single parameter which contains the
  9286. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9287. * src parameter of an <img> to display it.
  9288. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9289. * Check your browser for supported MIME types.
  9290. * @param samples Texture samples (default: 1)
  9291. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9292. * @param fileName A name for for the downloaded file.
  9293. * @constructor
  9294. */
  9295. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9296. if (mimeType === void 0) { mimeType = "image/png"; }
  9297. if (samples === void 0) { samples = 1; }
  9298. if (antialiasing === void 0) { antialiasing = false; }
  9299. var width;
  9300. var height;
  9301. //If a precision value is specified
  9302. if (size.precision) {
  9303. width = Math.round(engine.getRenderWidth() * size.precision);
  9304. height = Math.round(width / engine.getAspectRatio(camera));
  9305. size = { width: width, height: height };
  9306. }
  9307. else if (size.width && size.height) {
  9308. width = size.width;
  9309. height = size.height;
  9310. }
  9311. else if (size.width && !size.height) {
  9312. width = size.width;
  9313. height = Math.round(width / engine.getAspectRatio(camera));
  9314. size = { width: width, height: height };
  9315. }
  9316. else if (size.height && !size.width) {
  9317. height = size.height;
  9318. width = Math.round(height * engine.getAspectRatio(camera));
  9319. size = { width: width, height: height };
  9320. }
  9321. else if (!isNaN(size)) {
  9322. height = size;
  9323. width = size;
  9324. }
  9325. else {
  9326. Tools.Error("Invalid 'size' parameter !");
  9327. return;
  9328. }
  9329. var scene = camera.getScene();
  9330. var previousCamera = null;
  9331. if (scene.activeCamera !== camera) {
  9332. previousCamera = scene.activeCamera;
  9333. scene.activeCamera = camera;
  9334. }
  9335. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9336. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9337. texture.renderList = null;
  9338. texture.samples = samples;
  9339. if (antialiasing) {
  9340. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9341. }
  9342. texture.onAfterRenderObservable.add(function () {
  9343. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9344. });
  9345. scene.incrementRenderId();
  9346. scene.resetCachedMaterial();
  9347. texture.render(true);
  9348. texture.dispose();
  9349. if (previousCamera) {
  9350. scene.activeCamera = previousCamera;
  9351. }
  9352. camera.getProjectionMatrix(true); // Force cache refresh;
  9353. };
  9354. // XHR response validator for local file scenario
  9355. Tools.ValidateXHRData = function (xhr, dataType) {
  9356. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9357. if (dataType === void 0) { dataType = 7; }
  9358. try {
  9359. if (dataType & 1) {
  9360. if (xhr.responseText && xhr.responseText.length > 0) {
  9361. return true;
  9362. }
  9363. else if (dataType === 1) {
  9364. return false;
  9365. }
  9366. }
  9367. if (dataType & 2) {
  9368. // Check header width and height since there is no "TGA" magic number
  9369. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9370. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9371. return true;
  9372. }
  9373. else if (dataType === 2) {
  9374. return false;
  9375. }
  9376. }
  9377. if (dataType & 4) {
  9378. // Check for the "DDS" magic number
  9379. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9380. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9381. return true;
  9382. }
  9383. else {
  9384. return false;
  9385. }
  9386. }
  9387. }
  9388. catch (e) {
  9389. // Global protection
  9390. }
  9391. return false;
  9392. };
  9393. /**
  9394. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9395. * Be aware Math.random() could cause collisions, but:
  9396. * "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"
  9397. */
  9398. Tools.RandomId = function () {
  9399. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9400. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9401. return v.toString(16);
  9402. });
  9403. };
  9404. /**
  9405. * Test if the given uri is a base64 string.
  9406. * @param uri The uri to test
  9407. * @return True if the uri is a base64 string or false otherwise.
  9408. */
  9409. Tools.IsBase64 = function (uri) {
  9410. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9411. };
  9412. /**
  9413. * Decode the given base64 uri.
  9414. * @param uri The uri to decode
  9415. * @return The decoded base64 data.
  9416. */
  9417. Tools.DecodeBase64 = function (uri) {
  9418. var decodedString = atob(uri.split(",")[1]);
  9419. var bufferLength = decodedString.length;
  9420. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9421. for (var i = 0; i < bufferLength; i++) {
  9422. bufferView[i] = decodedString.charCodeAt(i);
  9423. }
  9424. return bufferView.buffer;
  9425. };
  9426. Object.defineProperty(Tools, "NoneLogLevel", {
  9427. get: function () {
  9428. return Tools._NoneLogLevel;
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. Object.defineProperty(Tools, "MessageLogLevel", {
  9434. get: function () {
  9435. return Tools._MessageLogLevel;
  9436. },
  9437. enumerable: true,
  9438. configurable: true
  9439. });
  9440. Object.defineProperty(Tools, "WarningLogLevel", {
  9441. get: function () {
  9442. return Tools._WarningLogLevel;
  9443. },
  9444. enumerable: true,
  9445. configurable: true
  9446. });
  9447. Object.defineProperty(Tools, "ErrorLogLevel", {
  9448. get: function () {
  9449. return Tools._ErrorLogLevel;
  9450. },
  9451. enumerable: true,
  9452. configurable: true
  9453. });
  9454. Object.defineProperty(Tools, "AllLogLevel", {
  9455. get: function () {
  9456. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9457. },
  9458. enumerable: true,
  9459. configurable: true
  9460. });
  9461. Tools._AddLogEntry = function (entry) {
  9462. Tools._LogCache = entry + Tools._LogCache;
  9463. if (Tools.OnNewCacheEntry) {
  9464. Tools.OnNewCacheEntry(entry);
  9465. }
  9466. };
  9467. Tools._FormatMessage = function (message) {
  9468. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9469. var date = new Date();
  9470. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9471. };
  9472. Tools._LogDisabled = function (message) {
  9473. // nothing to do
  9474. };
  9475. Tools._LogEnabled = function (message) {
  9476. var formattedMessage = Tools._FormatMessage(message);
  9477. console.log("BJS - " + formattedMessage);
  9478. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9479. Tools._AddLogEntry(entry);
  9480. };
  9481. Tools._WarnDisabled = function (message) {
  9482. // nothing to do
  9483. };
  9484. Tools._WarnEnabled = function (message) {
  9485. var formattedMessage = Tools._FormatMessage(message);
  9486. console.warn("BJS - " + formattedMessage);
  9487. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9488. Tools._AddLogEntry(entry);
  9489. };
  9490. Tools._ErrorDisabled = function (message) {
  9491. // nothing to do
  9492. };
  9493. Tools._ErrorEnabled = function (message) {
  9494. Tools.errorsCount++;
  9495. var formattedMessage = Tools._FormatMessage(message);
  9496. console.error("BJS - " + formattedMessage);
  9497. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9498. Tools._AddLogEntry(entry);
  9499. };
  9500. Object.defineProperty(Tools, "LogCache", {
  9501. get: function () {
  9502. return Tools._LogCache;
  9503. },
  9504. enumerable: true,
  9505. configurable: true
  9506. });
  9507. Tools.ClearLogCache = function () {
  9508. Tools._LogCache = "";
  9509. Tools.errorsCount = 0;
  9510. };
  9511. Object.defineProperty(Tools, "LogLevels", {
  9512. set: function (level) {
  9513. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9514. Tools.Log = Tools._LogEnabled;
  9515. }
  9516. else {
  9517. Tools.Log = Tools._LogDisabled;
  9518. }
  9519. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9520. Tools.Warn = Tools._WarnEnabled;
  9521. }
  9522. else {
  9523. Tools.Warn = Tools._WarnDisabled;
  9524. }
  9525. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9526. Tools.Error = Tools._ErrorEnabled;
  9527. }
  9528. else {
  9529. Tools.Error = Tools._ErrorDisabled;
  9530. }
  9531. },
  9532. enumerable: true,
  9533. configurable: true
  9534. });
  9535. Tools.IsWindowObjectExist = function () {
  9536. return (typeof window) !== "undefined";
  9537. };
  9538. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9539. get: function () {
  9540. return Tools._PerformanceNoneLogLevel;
  9541. },
  9542. enumerable: true,
  9543. configurable: true
  9544. });
  9545. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9546. get: function () {
  9547. return Tools._PerformanceUserMarkLogLevel;
  9548. },
  9549. enumerable: true,
  9550. configurable: true
  9551. });
  9552. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9553. get: function () {
  9554. return Tools._PerformanceConsoleLogLevel;
  9555. },
  9556. enumerable: true,
  9557. configurable: true
  9558. });
  9559. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9560. set: function (level) {
  9561. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9562. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9563. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9564. return;
  9565. }
  9566. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9567. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9568. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9569. return;
  9570. }
  9571. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9572. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9578. };
  9579. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9580. };
  9581. Tools._StartUserMark = function (counterName, condition) {
  9582. if (condition === void 0) { condition = true; }
  9583. if (!Tools._performance) {
  9584. if (!Tools.IsWindowObjectExist()) {
  9585. return;
  9586. }
  9587. Tools._performance = window.performance;
  9588. }
  9589. if (!condition || !Tools._performance.mark) {
  9590. return;
  9591. }
  9592. Tools._performance.mark(counterName + "-Begin");
  9593. };
  9594. Tools._EndUserMark = function (counterName, condition) {
  9595. if (condition === void 0) { condition = true; }
  9596. if (!condition || !Tools._performance.mark) {
  9597. return;
  9598. }
  9599. Tools._performance.mark(counterName + "-End");
  9600. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9601. };
  9602. Tools._StartPerformanceConsole = function (counterName, condition) {
  9603. if (condition === void 0) { condition = true; }
  9604. if (!condition) {
  9605. return;
  9606. }
  9607. Tools._StartUserMark(counterName, condition);
  9608. if (console.time) {
  9609. console.time(counterName);
  9610. }
  9611. };
  9612. Tools._EndPerformanceConsole = function (counterName, condition) {
  9613. if (condition === void 0) { condition = true; }
  9614. if (!condition) {
  9615. return;
  9616. }
  9617. Tools._EndUserMark(counterName, condition);
  9618. if (console.time) {
  9619. console.timeEnd(counterName);
  9620. }
  9621. };
  9622. Object.defineProperty(Tools, "Now", {
  9623. get: function () {
  9624. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9625. return window.performance.now();
  9626. }
  9627. return new Date().getTime();
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. /**
  9633. * This method will return the name of the class used to create the instance of the given object.
  9634. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9635. * @param object the object to get the class name from
  9636. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9637. */
  9638. Tools.GetClassName = function (object, isType) {
  9639. if (isType === void 0) { isType = false; }
  9640. var name = null;
  9641. if (!isType && object.getClassName) {
  9642. name = object.getClassName();
  9643. }
  9644. else {
  9645. if (object instanceof Object) {
  9646. var classObj = isType ? object : Object.getPrototypeOf(object);
  9647. name = classObj.constructor["__bjsclassName__"];
  9648. }
  9649. if (!name) {
  9650. name = typeof object;
  9651. }
  9652. }
  9653. return name;
  9654. };
  9655. Tools.First = function (array, predicate) {
  9656. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9657. var el = array_1[_i];
  9658. if (predicate(el)) {
  9659. return el;
  9660. }
  9661. }
  9662. return null;
  9663. };
  9664. /**
  9665. * This method will return the name of the full name of the class, including its owning module (if any).
  9666. * 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).
  9667. * @param object the object to get the class name from
  9668. * @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.
  9669. */
  9670. Tools.getFullClassName = function (object, isType) {
  9671. if (isType === void 0) { isType = false; }
  9672. var className = null;
  9673. var moduleName = null;
  9674. if (!isType && object.getClassName) {
  9675. className = object.getClassName();
  9676. }
  9677. else {
  9678. if (object instanceof Object) {
  9679. var classObj = isType ? object : Object.getPrototypeOf(object);
  9680. className = classObj.constructor["__bjsclassName__"];
  9681. moduleName = classObj.constructor["__bjsmoduleName__"];
  9682. }
  9683. if (!className) {
  9684. className = typeof object;
  9685. }
  9686. }
  9687. if (!className) {
  9688. return null;
  9689. }
  9690. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9691. };
  9692. /**
  9693. * 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.
  9694. * @param array
  9695. */
  9696. Tools.arrayOrStringFeeder = function (array) {
  9697. return function (index) {
  9698. if (index >= array.length) {
  9699. return null;
  9700. }
  9701. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9702. if (val && val.getHashCode) {
  9703. val = val.getHashCode();
  9704. }
  9705. if (typeof val === "string") {
  9706. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9707. }
  9708. return val;
  9709. };
  9710. };
  9711. /**
  9712. * Compute the hashCode of a stream of number
  9713. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9714. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9715. * @return the hash code computed
  9716. */
  9717. Tools.hashCodeFromStream = function (feeder) {
  9718. // Based from here: http://stackoverflow.com/a/7616484/802124
  9719. var hash = 0;
  9720. var index = 0;
  9721. var chr = feeder(index++);
  9722. while (chr != null) {
  9723. hash = ((hash << 5) - hash) + chr;
  9724. hash |= 0; // Convert to 32bit integer
  9725. chr = feeder(index++);
  9726. }
  9727. return hash;
  9728. };
  9729. /**
  9730. * Returns a promise that resolves after the given amount of time.
  9731. * @param delay Number of milliseconds to delay
  9732. * @returns Promise that resolves after the given amount of time
  9733. */
  9734. Tools.DelayAsync = function (delay) {
  9735. return new Promise(function (resolve) {
  9736. setTimeout(function () {
  9737. resolve();
  9738. }, delay);
  9739. });
  9740. };
  9741. Tools.BaseUrl = "";
  9742. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9743. /**
  9744. * Default behaviour for cors in the application.
  9745. * It can be a string if the expected behavior is identical in the entire app.
  9746. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9747. */
  9748. Tools.CorsBehavior = "anonymous";
  9749. Tools.UseFallbackTexture = true;
  9750. /**
  9751. * Use this object to register external classes like custom textures or material
  9752. * to allow the laoders to instantiate them
  9753. */
  9754. Tools.RegisteredExternalClasses = {};
  9755. // Used in case of a texture loading problem
  9756. 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";
  9757. Tools.PreprocessUrl = function (url) {
  9758. return url;
  9759. };
  9760. // Logs
  9761. Tools._NoneLogLevel = 0;
  9762. Tools._MessageLogLevel = 1;
  9763. Tools._WarningLogLevel = 2;
  9764. Tools._ErrorLogLevel = 4;
  9765. Tools._LogCache = "";
  9766. Tools.errorsCount = 0;
  9767. Tools.Log = Tools._LogEnabled;
  9768. Tools.Warn = Tools._WarnEnabled;
  9769. Tools.Error = Tools._ErrorEnabled;
  9770. // Performances
  9771. Tools._PerformanceNoneLogLevel = 0;
  9772. Tools._PerformanceUserMarkLogLevel = 1;
  9773. Tools._PerformanceConsoleLogLevel = 2;
  9774. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9775. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9776. return Tools;
  9777. }());
  9778. BABYLON.Tools = Tools;
  9779. /**
  9780. * This class is used to track a performance counter which is number based.
  9781. * The user has access to many properties which give statistics of different nature
  9782. *
  9783. * The implementer can track two kinds of Performance Counter: time and count
  9784. * 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.
  9785. * 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.
  9786. */
  9787. var PerfCounter = /** @class */ (function () {
  9788. function PerfCounter() {
  9789. this._startMonitoringTime = 0;
  9790. this._min = 0;
  9791. this._max = 0;
  9792. this._average = 0;
  9793. this._lastSecAverage = 0;
  9794. this._current = 0;
  9795. this._totalValueCount = 0;
  9796. this._totalAccumulated = 0;
  9797. this._lastSecAccumulated = 0;
  9798. this._lastSecTime = 0;
  9799. this._lastSecValueCount = 0;
  9800. }
  9801. Object.defineProperty(PerfCounter.prototype, "min", {
  9802. /**
  9803. * Returns the smallest value ever
  9804. */
  9805. get: function () {
  9806. return this._min;
  9807. },
  9808. enumerable: true,
  9809. configurable: true
  9810. });
  9811. Object.defineProperty(PerfCounter.prototype, "max", {
  9812. /**
  9813. * Returns the biggest value ever
  9814. */
  9815. get: function () {
  9816. return this._max;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(PerfCounter.prototype, "average", {
  9822. /**
  9823. * Returns the average value since the performance counter is running
  9824. */
  9825. get: function () {
  9826. return this._average;
  9827. },
  9828. enumerable: true,
  9829. configurable: true
  9830. });
  9831. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9832. /**
  9833. * Returns the average value of the last second the counter was monitored
  9834. */
  9835. get: function () {
  9836. return this._lastSecAverage;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(PerfCounter.prototype, "current", {
  9842. /**
  9843. * Returns the current value
  9844. */
  9845. get: function () {
  9846. return this._current;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(PerfCounter.prototype, "total", {
  9852. get: function () {
  9853. return this._totalAccumulated;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Object.defineProperty(PerfCounter.prototype, "count", {
  9859. get: function () {
  9860. return this._totalValueCount;
  9861. },
  9862. enumerable: true,
  9863. configurable: true
  9864. });
  9865. /**
  9866. * Call this method to start monitoring a new frame.
  9867. * 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.
  9868. */
  9869. PerfCounter.prototype.fetchNewFrame = function () {
  9870. this._totalValueCount++;
  9871. this._current = 0;
  9872. this._lastSecValueCount++;
  9873. };
  9874. /**
  9875. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9876. * @param newCount the count value to add to the monitored count
  9877. * @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.
  9878. */
  9879. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9880. if (!PerfCounter.Enabled) {
  9881. return;
  9882. }
  9883. this._current += newCount;
  9884. if (fetchResult) {
  9885. this._fetchResult();
  9886. }
  9887. };
  9888. /**
  9889. * Start monitoring this performance counter
  9890. */
  9891. PerfCounter.prototype.beginMonitoring = function () {
  9892. if (!PerfCounter.Enabled) {
  9893. return;
  9894. }
  9895. this._startMonitoringTime = Tools.Now;
  9896. };
  9897. /**
  9898. * Compute the time lapsed since the previous beginMonitoring() call.
  9899. * @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
  9900. */
  9901. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9902. if (newFrame === void 0) { newFrame = true; }
  9903. if (!PerfCounter.Enabled) {
  9904. return;
  9905. }
  9906. if (newFrame) {
  9907. this.fetchNewFrame();
  9908. }
  9909. var currentTime = Tools.Now;
  9910. this._current = currentTime - this._startMonitoringTime;
  9911. if (newFrame) {
  9912. this._fetchResult();
  9913. }
  9914. };
  9915. PerfCounter.prototype._fetchResult = function () {
  9916. this._totalAccumulated += this._current;
  9917. this._lastSecAccumulated += this._current;
  9918. // Min/Max update
  9919. this._min = Math.min(this._min, this._current);
  9920. this._max = Math.max(this._max, this._current);
  9921. this._average = this._totalAccumulated / this._totalValueCount;
  9922. // Reset last sec?
  9923. var now = Tools.Now;
  9924. if ((now - this._lastSecTime) > 1000) {
  9925. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9926. this._lastSecTime = now;
  9927. this._lastSecAccumulated = 0;
  9928. this._lastSecValueCount = 0;
  9929. }
  9930. };
  9931. PerfCounter.Enabled = true;
  9932. return PerfCounter;
  9933. }());
  9934. BABYLON.PerfCounter = PerfCounter;
  9935. /**
  9936. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9937. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9938. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9939. * @param name The name of the class, case should be preserved
  9940. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9941. */
  9942. function className(name, module) {
  9943. return function (target) {
  9944. target["__bjsclassName__"] = name;
  9945. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9946. };
  9947. }
  9948. BABYLON.className = className;
  9949. /**
  9950. * An implementation of a loop for asynchronous functions.
  9951. */
  9952. var AsyncLoop = /** @class */ (function () {
  9953. /**
  9954. * Constroctor.
  9955. * @param iterations the number of iterations.
  9956. * @param _fn the function to run each iteration
  9957. * @param _successCallback the callback that will be called upon succesful execution
  9958. * @param offset starting offset.
  9959. */
  9960. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9961. if (offset === void 0) { offset = 0; }
  9962. this.iterations = iterations;
  9963. this._fn = _fn;
  9964. this._successCallback = _successCallback;
  9965. this.index = offset - 1;
  9966. this._done = false;
  9967. }
  9968. /**
  9969. * Execute the next iteration. Must be called after the last iteration was finished.
  9970. */
  9971. AsyncLoop.prototype.executeNext = function () {
  9972. if (!this._done) {
  9973. if (this.index + 1 < this.iterations) {
  9974. ++this.index;
  9975. this._fn(this);
  9976. }
  9977. else {
  9978. this.breakLoop();
  9979. }
  9980. }
  9981. };
  9982. /**
  9983. * Break the loop and run the success callback.
  9984. */
  9985. AsyncLoop.prototype.breakLoop = function () {
  9986. this._done = true;
  9987. this._successCallback();
  9988. };
  9989. /**
  9990. * Helper function
  9991. */
  9992. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9993. if (offset === void 0) { offset = 0; }
  9994. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9995. loop.executeNext();
  9996. return loop;
  9997. };
  9998. /**
  9999. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10000. * @param iterations total number of iterations
  10001. * @param syncedIterations number of synchronous iterations in each async iteration.
  10002. * @param fn the function to call each iteration.
  10003. * @param callback a success call back that will be called when iterating stops.
  10004. * @param breakFunction a break condition (optional)
  10005. * @param timeout timeout settings for the setTimeout function. default - 0.
  10006. * @constructor
  10007. */
  10008. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10009. if (timeout === void 0) { timeout = 0; }
  10010. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10011. if (breakFunction && breakFunction())
  10012. loop.breakLoop();
  10013. else {
  10014. setTimeout(function () {
  10015. for (var i = 0; i < syncedIterations; ++i) {
  10016. var iteration = (loop.index * syncedIterations) + i;
  10017. if (iteration >= iterations)
  10018. break;
  10019. fn(iteration);
  10020. if (breakFunction && breakFunction()) {
  10021. loop.breakLoop();
  10022. break;
  10023. }
  10024. }
  10025. loop.executeNext();
  10026. }, timeout);
  10027. }
  10028. }, callback);
  10029. };
  10030. return AsyncLoop;
  10031. }());
  10032. BABYLON.AsyncLoop = AsyncLoop;
  10033. })(BABYLON || (BABYLON = {}));
  10034. //# sourceMappingURL=babylon.tools.js.map
  10035. "use strict";
  10036. var BABYLON;
  10037. (function (BABYLON) {
  10038. var PromiseStates;
  10039. (function (PromiseStates) {
  10040. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10041. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10042. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10043. })(PromiseStates || (PromiseStates = {}));
  10044. var FulFillmentAgregator = /** @class */ (function () {
  10045. function FulFillmentAgregator() {
  10046. this.count = 0;
  10047. this.target = 0;
  10048. this.results = [];
  10049. }
  10050. return FulFillmentAgregator;
  10051. }());
  10052. var InternalPromise = /** @class */ (function () {
  10053. function InternalPromise(resolver) {
  10054. var _this = this;
  10055. this._state = PromiseStates.Pending;
  10056. this._children = new Array();
  10057. this._rejectWasConsumed = false;
  10058. if (!resolver) {
  10059. return;
  10060. }
  10061. try {
  10062. resolver(function (value) {
  10063. _this._resolve(value);
  10064. }, function (reason) {
  10065. _this._reject(reason);
  10066. });
  10067. }
  10068. catch (e) {
  10069. this._reject(e);
  10070. }
  10071. }
  10072. InternalPromise.prototype.catch = function (onRejected) {
  10073. return this.then(undefined, onRejected);
  10074. };
  10075. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10076. var _this = this;
  10077. var newPromise = new InternalPromise();
  10078. newPromise._onFulfilled = onFulfilled;
  10079. newPromise._onRejected = onRejected;
  10080. // Composition
  10081. this._children.push(newPromise);
  10082. if (this._state !== PromiseStates.Pending) {
  10083. BABYLON.Tools.SetImmediate(function () {
  10084. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10085. var returnedValue = newPromise._resolve(_this._result);
  10086. if (returnedValue !== undefined && returnedValue !== null) {
  10087. if (returnedValue._state !== undefined) {
  10088. var returnedPromise = returnedValue;
  10089. newPromise._children.push(returnedPromise);
  10090. newPromise = returnedPromise;
  10091. }
  10092. else {
  10093. newPromise._result = returnedValue;
  10094. }
  10095. }
  10096. }
  10097. else {
  10098. newPromise._reject(_this._reason);
  10099. }
  10100. });
  10101. }
  10102. return newPromise;
  10103. };
  10104. InternalPromise.prototype._moveChildren = function (children) {
  10105. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10106. if (this._state === PromiseStates.Fulfilled) {
  10107. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10108. var child = _b[_i];
  10109. child._resolve(this._result);
  10110. }
  10111. }
  10112. else if (this._state === PromiseStates.Rejected) {
  10113. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10114. var child = _d[_c];
  10115. child._reject(this._reason);
  10116. }
  10117. }
  10118. var _a;
  10119. };
  10120. InternalPromise.prototype._resolve = function (value) {
  10121. try {
  10122. this._state = PromiseStates.Fulfilled;
  10123. var returnedValue = null;
  10124. if (this._onFulfilled) {
  10125. returnedValue = this._onFulfilled(value);
  10126. }
  10127. if (returnedValue !== undefined && returnedValue !== null) {
  10128. if (returnedValue._state !== undefined) {
  10129. // Transmit children
  10130. var returnedPromise = returnedValue;
  10131. returnedPromise._moveChildren(this._children);
  10132. value = returnedPromise._result;
  10133. }
  10134. else {
  10135. value = returnedValue;
  10136. }
  10137. }
  10138. this._result = value;
  10139. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10140. var child = _a[_i];
  10141. child._resolve(value);
  10142. }
  10143. this._children.length = 0;
  10144. delete this._onFulfilled;
  10145. delete this._onRejected;
  10146. }
  10147. catch (e) {
  10148. this._reject(e, true);
  10149. }
  10150. };
  10151. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10152. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10153. this._state = PromiseStates.Rejected;
  10154. this._reason = reason;
  10155. if (this._onRejected && !onLocalThrow) {
  10156. try {
  10157. this._onRejected(reason);
  10158. this._rejectWasConsumed = true;
  10159. }
  10160. catch (e) {
  10161. reason = e;
  10162. }
  10163. }
  10164. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10165. var child = _a[_i];
  10166. if (this._rejectWasConsumed) {
  10167. child._resolve(null);
  10168. }
  10169. else {
  10170. child._reject(reason);
  10171. }
  10172. }
  10173. this._children.length = 0;
  10174. delete this._onFulfilled;
  10175. delete this._onRejected;
  10176. };
  10177. InternalPromise.resolve = function (value) {
  10178. var newPromise = new InternalPromise();
  10179. newPromise._resolve(value);
  10180. return newPromise;
  10181. };
  10182. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10183. promise.then(function (value) {
  10184. agregator.results[index] = value;
  10185. agregator.count++;
  10186. if (agregator.count === agregator.target) {
  10187. agregator.rootPromise._resolve(agregator.results);
  10188. }
  10189. return null;
  10190. }, function (reason) {
  10191. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10192. agregator.rootPromise._reject(reason);
  10193. }
  10194. });
  10195. };
  10196. InternalPromise.all = function (promises) {
  10197. var newPromise = new InternalPromise();
  10198. var agregator = new FulFillmentAgregator();
  10199. agregator.target = promises.length;
  10200. agregator.rootPromise = newPromise;
  10201. if (promises.length) {
  10202. for (var index = 0; index < promises.length; index++) {
  10203. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10204. }
  10205. }
  10206. else {
  10207. newPromise._resolve([]);
  10208. }
  10209. return newPromise;
  10210. };
  10211. InternalPromise.race = function (promises) {
  10212. var newPromise = new InternalPromise();
  10213. if (promises.length) {
  10214. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10215. var promise = promises_1[_i];
  10216. promise.then(function (value) {
  10217. if (newPromise) {
  10218. newPromise._resolve(value);
  10219. newPromise = null;
  10220. }
  10221. return null;
  10222. }, function (reason) {
  10223. if (newPromise) {
  10224. newPromise._reject(reason);
  10225. newPromise = null;
  10226. }
  10227. });
  10228. }
  10229. }
  10230. return newPromise;
  10231. };
  10232. return InternalPromise;
  10233. }());
  10234. /**
  10235. * Helper class that provides a small promise polyfill
  10236. */
  10237. var PromisePolyfill = /** @class */ (function () {
  10238. function PromisePolyfill() {
  10239. }
  10240. /**
  10241. * Static function used to check if the polyfill is required
  10242. * If this is the case then the function will inject the polyfill to window.Promise
  10243. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10244. */
  10245. PromisePolyfill.Apply = function (force) {
  10246. if (force === void 0) { force = false; }
  10247. if (force || typeof Promise === 'undefined') {
  10248. var root = window;
  10249. root.Promise = InternalPromise;
  10250. }
  10251. };
  10252. return PromisePolyfill;
  10253. }());
  10254. BABYLON.PromisePolyfill = PromisePolyfill;
  10255. })(BABYLON || (BABYLON = {}));
  10256. //# sourceMappingURL=babylon.promise.js.map
  10257. "use strict";
  10258. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10259. var BABYLON;
  10260. (function (BABYLON) {
  10261. /**
  10262. * Helper class to push actions to a pool of workers.
  10263. */
  10264. var WorkerPool = /** @class */ (function () {
  10265. /**
  10266. * Constructor
  10267. * @param workers Array of workers to use for actions
  10268. */
  10269. function WorkerPool(workers) {
  10270. this._pendingActions = new Array();
  10271. this._workerInfos = workers.map(function (worker) { return ({
  10272. worker: worker,
  10273. active: false
  10274. }); });
  10275. }
  10276. /**
  10277. * Terminates all workers and clears any pending actions.
  10278. */
  10279. WorkerPool.prototype.dispose = function () {
  10280. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10281. var workerInfo = _a[_i];
  10282. workerInfo.worker.terminate();
  10283. }
  10284. delete this._workerInfos;
  10285. delete this._pendingActions;
  10286. };
  10287. /**
  10288. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10289. * pended until a worker has completed its action.
  10290. * @param action The action to perform. Call onComplete when the action is complete.
  10291. */
  10292. WorkerPool.prototype.push = function (action) {
  10293. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10294. var workerInfo = _a[_i];
  10295. if (!workerInfo.active) {
  10296. this._execute(workerInfo, action);
  10297. return;
  10298. }
  10299. }
  10300. this._pendingActions.push(action);
  10301. };
  10302. WorkerPool.prototype._execute = function (workerInfo, action) {
  10303. var _this = this;
  10304. workerInfo.active = true;
  10305. action(workerInfo.worker, function () {
  10306. workerInfo.active = false;
  10307. var nextAction = _this._pendingActions.shift();
  10308. if (nextAction) {
  10309. _this._execute(workerInfo, nextAction);
  10310. }
  10311. });
  10312. };
  10313. return WorkerPool;
  10314. }());
  10315. BABYLON.WorkerPool = WorkerPool;
  10316. })(BABYLON || (BABYLON = {}));
  10317. //# sourceMappingURL=babylon.workerPool.js.map
  10318. "use strict";
  10319. var BABYLON;
  10320. (function (BABYLON) {
  10321. var _AlphaState = /** @class */ (function () {
  10322. /**
  10323. * Initializes the state.
  10324. */
  10325. function _AlphaState() {
  10326. this._isAlphaBlendDirty = false;
  10327. this._isBlendFunctionParametersDirty = false;
  10328. this._isBlendEquationParametersDirty = false;
  10329. this._isBlendConstantsDirty = false;
  10330. this._alphaBlend = false;
  10331. this._blendFunctionParameters = new Array(4);
  10332. this._blendEquationParameters = new Array(2);
  10333. this._blendConstants = new Array(4);
  10334. this.reset();
  10335. }
  10336. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10337. get: function () {
  10338. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10339. },
  10340. enumerable: true,
  10341. configurable: true
  10342. });
  10343. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10344. get: function () {
  10345. return this._alphaBlend;
  10346. },
  10347. set: function (value) {
  10348. if (this._alphaBlend === value) {
  10349. return;
  10350. }
  10351. this._alphaBlend = value;
  10352. this._isAlphaBlendDirty = true;
  10353. },
  10354. enumerable: true,
  10355. configurable: true
  10356. });
  10357. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10358. if (this._blendConstants[0] === r &&
  10359. this._blendConstants[1] === g &&
  10360. this._blendConstants[2] === b &&
  10361. this._blendConstants[3] === a) {
  10362. return;
  10363. }
  10364. this._blendConstants[0] = r;
  10365. this._blendConstants[1] = g;
  10366. this._blendConstants[2] = b;
  10367. this._blendConstants[3] = a;
  10368. this._isBlendConstantsDirty = true;
  10369. };
  10370. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10371. if (this._blendFunctionParameters[0] === value0 &&
  10372. this._blendFunctionParameters[1] === value1 &&
  10373. this._blendFunctionParameters[2] === value2 &&
  10374. this._blendFunctionParameters[3] === value3) {
  10375. return;
  10376. }
  10377. this._blendFunctionParameters[0] = value0;
  10378. this._blendFunctionParameters[1] = value1;
  10379. this._blendFunctionParameters[2] = value2;
  10380. this._blendFunctionParameters[3] = value3;
  10381. this._isBlendFunctionParametersDirty = true;
  10382. };
  10383. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10384. if (this._blendEquationParameters[0] === rgb &&
  10385. this._blendEquationParameters[1] === alpha) {
  10386. return;
  10387. }
  10388. this._blendEquationParameters[0] = rgb;
  10389. this._blendEquationParameters[1] = alpha;
  10390. this._isBlendEquationParametersDirty = true;
  10391. };
  10392. _AlphaState.prototype.reset = function () {
  10393. this._alphaBlend = false;
  10394. this._blendFunctionParameters[0] = null;
  10395. this._blendFunctionParameters[1] = null;
  10396. this._blendFunctionParameters[2] = null;
  10397. this._blendFunctionParameters[3] = null;
  10398. this._blendEquationParameters[0] = null;
  10399. this._blendEquationParameters[1] = null;
  10400. this._blendConstants[0] = null;
  10401. this._blendConstants[1] = null;
  10402. this._blendConstants[2] = null;
  10403. this._blendConstants[3] = null;
  10404. this._isAlphaBlendDirty = true;
  10405. this._isBlendFunctionParametersDirty = false;
  10406. this._isBlendEquationParametersDirty = false;
  10407. this._isBlendConstantsDirty = false;
  10408. };
  10409. _AlphaState.prototype.apply = function (gl) {
  10410. if (!this.isDirty) {
  10411. return;
  10412. }
  10413. // Alpha blend
  10414. if (this._isAlphaBlendDirty) {
  10415. if (this._alphaBlend) {
  10416. gl.enable(gl.BLEND);
  10417. }
  10418. else {
  10419. gl.disable(gl.BLEND);
  10420. }
  10421. this._isAlphaBlendDirty = false;
  10422. }
  10423. // Alpha function
  10424. if (this._isBlendFunctionParametersDirty) {
  10425. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10426. this._isBlendFunctionParametersDirty = false;
  10427. }
  10428. // Alpha equation
  10429. if (this._isBlendEquationParametersDirty) {
  10430. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10431. this._isBlendEquationParametersDirty = false;
  10432. }
  10433. // Constants
  10434. if (this._isBlendConstantsDirty) {
  10435. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10436. this._isBlendConstantsDirty = false;
  10437. }
  10438. };
  10439. return _AlphaState;
  10440. }());
  10441. BABYLON._AlphaState = _AlphaState;
  10442. })(BABYLON || (BABYLON = {}));
  10443. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10444. "use strict";
  10445. var BABYLON;
  10446. (function (BABYLON) {
  10447. var _DepthCullingState = /** @class */ (function () {
  10448. /**
  10449. * Initializes the state.
  10450. */
  10451. function _DepthCullingState() {
  10452. this._isDepthTestDirty = false;
  10453. this._isDepthMaskDirty = false;
  10454. this._isDepthFuncDirty = false;
  10455. this._isCullFaceDirty = false;
  10456. this._isCullDirty = false;
  10457. this._isZOffsetDirty = false;
  10458. this._isFrontFaceDirty = false;
  10459. this.reset();
  10460. }
  10461. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10462. get: function () {
  10463. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10464. },
  10465. enumerable: true,
  10466. configurable: true
  10467. });
  10468. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10469. get: function () {
  10470. return this._zOffset;
  10471. },
  10472. set: function (value) {
  10473. if (this._zOffset === value) {
  10474. return;
  10475. }
  10476. this._zOffset = value;
  10477. this._isZOffsetDirty = true;
  10478. },
  10479. enumerable: true,
  10480. configurable: true
  10481. });
  10482. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10483. get: function () {
  10484. return this._cullFace;
  10485. },
  10486. set: function (value) {
  10487. if (this._cullFace === value) {
  10488. return;
  10489. }
  10490. this._cullFace = value;
  10491. this._isCullFaceDirty = true;
  10492. },
  10493. enumerable: true,
  10494. configurable: true
  10495. });
  10496. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10497. get: function () {
  10498. return this._cull;
  10499. },
  10500. set: function (value) {
  10501. if (this._cull === value) {
  10502. return;
  10503. }
  10504. this._cull = value;
  10505. this._isCullDirty = true;
  10506. },
  10507. enumerable: true,
  10508. configurable: true
  10509. });
  10510. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10511. get: function () {
  10512. return this._depthFunc;
  10513. },
  10514. set: function (value) {
  10515. if (this._depthFunc === value) {
  10516. return;
  10517. }
  10518. this._depthFunc = value;
  10519. this._isDepthFuncDirty = true;
  10520. },
  10521. enumerable: true,
  10522. configurable: true
  10523. });
  10524. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10525. get: function () {
  10526. return this._depthMask;
  10527. },
  10528. set: function (value) {
  10529. if (this._depthMask === value) {
  10530. return;
  10531. }
  10532. this._depthMask = value;
  10533. this._isDepthMaskDirty = true;
  10534. },
  10535. enumerable: true,
  10536. configurable: true
  10537. });
  10538. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10539. get: function () {
  10540. return this._depthTest;
  10541. },
  10542. set: function (value) {
  10543. if (this._depthTest === value) {
  10544. return;
  10545. }
  10546. this._depthTest = value;
  10547. this._isDepthTestDirty = true;
  10548. },
  10549. enumerable: true,
  10550. configurable: true
  10551. });
  10552. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10553. get: function () {
  10554. return this._frontFace;
  10555. },
  10556. set: function (value) {
  10557. if (this._frontFace === value) {
  10558. return;
  10559. }
  10560. this._frontFace = value;
  10561. this._isFrontFaceDirty = true;
  10562. },
  10563. enumerable: true,
  10564. configurable: true
  10565. });
  10566. _DepthCullingState.prototype.reset = function () {
  10567. this._depthMask = true;
  10568. this._depthTest = true;
  10569. this._depthFunc = null;
  10570. this._cullFace = null;
  10571. this._cull = null;
  10572. this._zOffset = 0;
  10573. this._frontFace = null;
  10574. this._isDepthTestDirty = true;
  10575. this._isDepthMaskDirty = true;
  10576. this._isDepthFuncDirty = false;
  10577. this._isCullFaceDirty = false;
  10578. this._isCullDirty = false;
  10579. this._isZOffsetDirty = false;
  10580. this._isFrontFaceDirty = false;
  10581. };
  10582. _DepthCullingState.prototype.apply = function (gl) {
  10583. if (!this.isDirty) {
  10584. return;
  10585. }
  10586. // Cull
  10587. if (this._isCullDirty) {
  10588. if (this.cull) {
  10589. gl.enable(gl.CULL_FACE);
  10590. }
  10591. else {
  10592. gl.disable(gl.CULL_FACE);
  10593. }
  10594. this._isCullDirty = false;
  10595. }
  10596. // Cull face
  10597. if (this._isCullFaceDirty) {
  10598. gl.cullFace(this.cullFace);
  10599. this._isCullFaceDirty = false;
  10600. }
  10601. // Depth mask
  10602. if (this._isDepthMaskDirty) {
  10603. gl.depthMask(this.depthMask);
  10604. this._isDepthMaskDirty = false;
  10605. }
  10606. // Depth test
  10607. if (this._isDepthTestDirty) {
  10608. if (this.depthTest) {
  10609. gl.enable(gl.DEPTH_TEST);
  10610. }
  10611. else {
  10612. gl.disable(gl.DEPTH_TEST);
  10613. }
  10614. this._isDepthTestDirty = false;
  10615. }
  10616. // Depth func
  10617. if (this._isDepthFuncDirty) {
  10618. gl.depthFunc(this.depthFunc);
  10619. this._isDepthFuncDirty = false;
  10620. }
  10621. // zOffset
  10622. if (this._isZOffsetDirty) {
  10623. if (this.zOffset) {
  10624. gl.enable(gl.POLYGON_OFFSET_FILL);
  10625. gl.polygonOffset(this.zOffset, 0);
  10626. }
  10627. else {
  10628. gl.disable(gl.POLYGON_OFFSET_FILL);
  10629. }
  10630. this._isZOffsetDirty = false;
  10631. }
  10632. // Front face
  10633. if (this._isFrontFaceDirty) {
  10634. gl.frontFace(this.frontFace);
  10635. this._isFrontFaceDirty = false;
  10636. }
  10637. };
  10638. return _DepthCullingState;
  10639. }());
  10640. BABYLON._DepthCullingState = _DepthCullingState;
  10641. })(BABYLON || (BABYLON = {}));
  10642. //# sourceMappingURL=babylon.depthCullingState.js.map
  10643. "use strict";
  10644. var BABYLON;
  10645. (function (BABYLON) {
  10646. var _StencilState = /** @class */ (function () {
  10647. function _StencilState() {
  10648. this._isStencilTestDirty = false;
  10649. this._isStencilMaskDirty = false;
  10650. this._isStencilFuncDirty = false;
  10651. this._isStencilOpDirty = false;
  10652. this.reset();
  10653. }
  10654. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10655. get: function () {
  10656. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10657. },
  10658. enumerable: true,
  10659. configurable: true
  10660. });
  10661. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10662. get: function () {
  10663. return this._stencilFunc;
  10664. },
  10665. set: function (value) {
  10666. if (this._stencilFunc === value) {
  10667. return;
  10668. }
  10669. this._stencilFunc = value;
  10670. this._isStencilFuncDirty = true;
  10671. },
  10672. enumerable: true,
  10673. configurable: true
  10674. });
  10675. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10676. get: function () {
  10677. return this._stencilFuncRef;
  10678. },
  10679. set: function (value) {
  10680. if (this._stencilFuncRef === value) {
  10681. return;
  10682. }
  10683. this._stencilFuncRef = value;
  10684. this._isStencilFuncDirty = true;
  10685. },
  10686. enumerable: true,
  10687. configurable: true
  10688. });
  10689. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10690. get: function () {
  10691. return this._stencilFuncMask;
  10692. },
  10693. set: function (value) {
  10694. if (this._stencilFuncMask === value) {
  10695. return;
  10696. }
  10697. this._stencilFuncMask = value;
  10698. this._isStencilFuncDirty = true;
  10699. },
  10700. enumerable: true,
  10701. configurable: true
  10702. });
  10703. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10704. get: function () {
  10705. return this._stencilOpStencilFail;
  10706. },
  10707. set: function (value) {
  10708. if (this._stencilOpStencilFail === value) {
  10709. return;
  10710. }
  10711. this._stencilOpStencilFail = value;
  10712. this._isStencilOpDirty = true;
  10713. },
  10714. enumerable: true,
  10715. configurable: true
  10716. });
  10717. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10718. get: function () {
  10719. return this._stencilOpDepthFail;
  10720. },
  10721. set: function (value) {
  10722. if (this._stencilOpDepthFail === value) {
  10723. return;
  10724. }
  10725. this._stencilOpDepthFail = value;
  10726. this._isStencilOpDirty = true;
  10727. },
  10728. enumerable: true,
  10729. configurable: true
  10730. });
  10731. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10732. get: function () {
  10733. return this._stencilOpStencilDepthPass;
  10734. },
  10735. set: function (value) {
  10736. if (this._stencilOpStencilDepthPass === value) {
  10737. return;
  10738. }
  10739. this._stencilOpStencilDepthPass = value;
  10740. this._isStencilOpDirty = true;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10746. get: function () {
  10747. return this._stencilMask;
  10748. },
  10749. set: function (value) {
  10750. if (this._stencilMask === value) {
  10751. return;
  10752. }
  10753. this._stencilMask = value;
  10754. this._isStencilMaskDirty = true;
  10755. },
  10756. enumerable: true,
  10757. configurable: true
  10758. });
  10759. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10760. get: function () {
  10761. return this._stencilTest;
  10762. },
  10763. set: function (value) {
  10764. if (this._stencilTest === value) {
  10765. return;
  10766. }
  10767. this._stencilTest = value;
  10768. this._isStencilTestDirty = true;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. _StencilState.prototype.reset = function () {
  10774. this._stencilTest = false;
  10775. this._stencilMask = 0xFF;
  10776. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10777. this._stencilFuncRef = 1;
  10778. this._stencilFuncMask = 0xFF;
  10779. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10780. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10781. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10782. this._isStencilTestDirty = true;
  10783. this._isStencilMaskDirty = true;
  10784. this._isStencilFuncDirty = true;
  10785. this._isStencilOpDirty = true;
  10786. };
  10787. _StencilState.prototype.apply = function (gl) {
  10788. if (!this.isDirty) {
  10789. return;
  10790. }
  10791. // Stencil test
  10792. if (this._isStencilTestDirty) {
  10793. if (this.stencilTest) {
  10794. gl.enable(gl.STENCIL_TEST);
  10795. }
  10796. else {
  10797. gl.disable(gl.STENCIL_TEST);
  10798. }
  10799. this._isStencilTestDirty = false;
  10800. }
  10801. // Stencil mask
  10802. if (this._isStencilMaskDirty) {
  10803. gl.stencilMask(this.stencilMask);
  10804. this._isStencilMaskDirty = false;
  10805. }
  10806. // Stencil func
  10807. if (this._isStencilFuncDirty) {
  10808. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10809. this._isStencilFuncDirty = false;
  10810. }
  10811. // Stencil op
  10812. if (this._isStencilOpDirty) {
  10813. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10814. this._isStencilOpDirty = false;
  10815. }
  10816. };
  10817. return _StencilState;
  10818. }());
  10819. BABYLON._StencilState = _StencilState;
  10820. })(BABYLON || (BABYLON = {}));
  10821. //# sourceMappingURL=babylon.stencilState.js.map
  10822. "use strict";
  10823. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10824. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10825. s = arguments[i];
  10826. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10827. t[p] = s[p];
  10828. }
  10829. return t;
  10830. };
  10831. var BABYLON;
  10832. (function (BABYLON) {
  10833. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10834. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10835. };
  10836. var compileRawShader = function (gl, source, type) {
  10837. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10838. gl.shaderSource(shader, source);
  10839. gl.compileShader(shader);
  10840. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10841. var log = gl.getShaderInfoLog(shader);
  10842. if (log) {
  10843. throw new Error(log);
  10844. }
  10845. }
  10846. if (!shader) {
  10847. throw new Error("Something went wrong while compile the shader.");
  10848. }
  10849. return shader;
  10850. };
  10851. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10852. var magFilter = gl.NEAREST;
  10853. var minFilter = gl.NEAREST;
  10854. switch (samplingMode) {
  10855. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10856. magFilter = gl.LINEAR;
  10857. if (generateMipMaps) {
  10858. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10859. }
  10860. else {
  10861. minFilter = gl.LINEAR;
  10862. }
  10863. break;
  10864. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10865. magFilter = gl.LINEAR;
  10866. if (generateMipMaps) {
  10867. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10868. }
  10869. else {
  10870. minFilter = gl.LINEAR;
  10871. }
  10872. break;
  10873. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10874. magFilter = gl.NEAREST;
  10875. if (generateMipMaps) {
  10876. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10877. }
  10878. else {
  10879. minFilter = gl.NEAREST;
  10880. }
  10881. break;
  10882. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10883. magFilter = gl.NEAREST;
  10884. if (generateMipMaps) {
  10885. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10886. }
  10887. else {
  10888. minFilter = gl.NEAREST;
  10889. }
  10890. break;
  10891. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10892. magFilter = gl.NEAREST;
  10893. if (generateMipMaps) {
  10894. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10895. }
  10896. else {
  10897. minFilter = gl.LINEAR;
  10898. }
  10899. break;
  10900. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10901. magFilter = gl.NEAREST;
  10902. if (generateMipMaps) {
  10903. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10904. }
  10905. else {
  10906. minFilter = gl.LINEAR;
  10907. }
  10908. break;
  10909. case BABYLON.Texture.NEAREST_LINEAR:
  10910. magFilter = gl.NEAREST;
  10911. minFilter = gl.LINEAR;
  10912. break;
  10913. case BABYLON.Texture.NEAREST_NEAREST:
  10914. magFilter = gl.NEAREST;
  10915. minFilter = gl.NEAREST;
  10916. break;
  10917. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10918. magFilter = gl.LINEAR;
  10919. if (generateMipMaps) {
  10920. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10921. }
  10922. else {
  10923. minFilter = gl.NEAREST;
  10924. }
  10925. break;
  10926. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10927. magFilter = gl.LINEAR;
  10928. if (generateMipMaps) {
  10929. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10930. }
  10931. else {
  10932. minFilter = gl.NEAREST;
  10933. }
  10934. break;
  10935. case BABYLON.Texture.LINEAR_LINEAR:
  10936. magFilter = gl.LINEAR;
  10937. minFilter = gl.LINEAR;
  10938. break;
  10939. case BABYLON.Texture.LINEAR_NEAREST:
  10940. magFilter = gl.LINEAR;
  10941. minFilter = gl.NEAREST;
  10942. break;
  10943. }
  10944. return {
  10945. min: minFilter,
  10946. mag: magFilter
  10947. };
  10948. };
  10949. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10950. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10951. var img;
  10952. var onload = function () {
  10953. loadedImages[index] = img;
  10954. loadedImages._internalCount++;
  10955. if (scene) {
  10956. scene._removePendingData(img);
  10957. }
  10958. if (loadedImages._internalCount === 6) {
  10959. onfinish(loadedImages);
  10960. }
  10961. };
  10962. var onerror = function (message, exception) {
  10963. if (scene) {
  10964. scene._removePendingData(img);
  10965. }
  10966. if (onErrorCallBack) {
  10967. onErrorCallBack(message, exception);
  10968. }
  10969. };
  10970. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10971. if (scene) {
  10972. scene._addPendingData(img);
  10973. }
  10974. };
  10975. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10976. if (onError === void 0) { onError = null; }
  10977. var loadedImages = [];
  10978. loadedImages._internalCount = 0;
  10979. for (var index = 0; index < 6; index++) {
  10980. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10981. }
  10982. };
  10983. var BufferPointer = /** @class */ (function () {
  10984. function BufferPointer() {
  10985. }
  10986. return BufferPointer;
  10987. }());
  10988. /**
  10989. * Interface for attribute information associated with buffer instanciation
  10990. */
  10991. var InstancingAttributeInfo = /** @class */ (function () {
  10992. function InstancingAttributeInfo() {
  10993. }
  10994. return InstancingAttributeInfo;
  10995. }());
  10996. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10997. /**
  10998. * Define options used to create a render target texture
  10999. */
  11000. var RenderTargetCreationOptions = /** @class */ (function () {
  11001. function RenderTargetCreationOptions() {
  11002. }
  11003. return RenderTargetCreationOptions;
  11004. }());
  11005. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11006. /**
  11007. * Define options used to create a depth texture
  11008. */
  11009. var DepthTextureCreationOptions = /** @class */ (function () {
  11010. function DepthTextureCreationOptions() {
  11011. }
  11012. return DepthTextureCreationOptions;
  11013. }());
  11014. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11015. /**
  11016. * Class used to describe the capabilities of the engine relatively to the current browser
  11017. */
  11018. var EngineCapabilities = /** @class */ (function () {
  11019. function EngineCapabilities() {
  11020. }
  11021. return EngineCapabilities;
  11022. }());
  11023. BABYLON.EngineCapabilities = EngineCapabilities;
  11024. /**
  11025. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11026. */
  11027. var Engine = /** @class */ (function () {
  11028. /**
  11029. * Creates a new engine
  11030. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11031. * @param antialias defines enable antialiasing (default: false)
  11032. * @param options defines further options to be sent to the getContext() function
  11033. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11034. */
  11035. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11036. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11037. var _this = this;
  11038. // Public members
  11039. /**
  11040. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11041. */
  11042. this.forcePOTTextures = false;
  11043. /**
  11044. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11045. */
  11046. this.isFullscreen = false;
  11047. /**
  11048. * Gets a boolean indicating if the pointer is currently locked
  11049. */
  11050. this.isPointerLock = false;
  11051. /**
  11052. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11053. */
  11054. this.cullBackFaces = true;
  11055. /**
  11056. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11057. */
  11058. this.renderEvenInBackground = true;
  11059. /**
  11060. * Gets or sets a boolean indicating that cache can be kept between frames
  11061. */
  11062. this.preventCacheWipeBetweenFrames = false;
  11063. /**
  11064. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11065. **/
  11066. this.enableOfflineSupport = false;
  11067. /**
  11068. * Gets the list of created scenes
  11069. */
  11070. this.scenes = new Array();
  11071. /**
  11072. * Gets the list of created postprocesses
  11073. */
  11074. this.postProcesses = new Array();
  11075. // Observables
  11076. /**
  11077. * Observable event triggered each time the rendering canvas is resized
  11078. */
  11079. this.onResizeObservable = new BABYLON.Observable();
  11080. /**
  11081. * Observable event triggered each time the canvas loses focus
  11082. */
  11083. this.onCanvasBlurObservable = new BABYLON.Observable();
  11084. /**
  11085. * Observable event triggered each time the canvas gains focus
  11086. */
  11087. this.onCanvasFocusObservable = new BABYLON.Observable();
  11088. /**
  11089. * Observable event triggered each time the canvas receives pointerout event
  11090. */
  11091. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11092. /**
  11093. * Observable event triggered before each texture is initialized
  11094. */
  11095. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11096. //WebVR
  11097. this._vrDisplay = undefined;
  11098. this._vrSupported = false;
  11099. this._vrExclusivePointerMode = false;
  11100. // Uniform buffers list
  11101. /**
  11102. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11103. */
  11104. this.disableUniformBuffers = false;
  11105. /** @ignore */
  11106. this._uniformBuffers = new Array();
  11107. // Observables
  11108. /**
  11109. * Observable raised when the engine begins a new frame
  11110. */
  11111. this.onBeginFrameObservable = new BABYLON.Observable();
  11112. /**
  11113. * Observable raised when the engine ends the current frame
  11114. */
  11115. this.onEndFrameObservable = new BABYLON.Observable();
  11116. /**
  11117. * Observable raised when the engine is about to compile a shader
  11118. */
  11119. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11120. /**
  11121. * Observable raised when the engine has jsut compiled a shader
  11122. */
  11123. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11124. this._windowIsBackground = false;
  11125. this._webGLVersion = 1.0;
  11126. /** @ignore */
  11127. this._badOS = false;
  11128. /** @ignore */
  11129. this._badDesktopOS = false;
  11130. /**
  11131. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11132. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11133. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11134. */
  11135. this.disableTextureBindingOptimization = false;
  11136. /**
  11137. * Observable signaled when VR display mode changes
  11138. */
  11139. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11140. /**
  11141. * Observable signaled when VR request present is complete
  11142. */
  11143. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11144. /**
  11145. * Observable signaled when VR request present starts
  11146. */
  11147. this.onVRRequestPresentStart = new BABYLON.Observable();
  11148. this._colorWrite = true;
  11149. /** @ignore */
  11150. this._drawCalls = new BABYLON.PerfCounter();
  11151. /** @ignore */
  11152. this._textureCollisions = new BABYLON.PerfCounter();
  11153. this._renderingQueueLaunched = false;
  11154. this._activeRenderLoops = new Array();
  11155. // Deterministic lockstepMaxSteps
  11156. this._deterministicLockstep = false;
  11157. this._lockstepMaxSteps = 4;
  11158. // Lost context
  11159. /**
  11160. * Observable signaled when a context lost event is raised
  11161. */
  11162. this.onContextLostObservable = new BABYLON.Observable();
  11163. /**
  11164. * Observable signaled when a context restored event is raised
  11165. */
  11166. this.onContextRestoredObservable = new BABYLON.Observable();
  11167. this._contextWasLost = false;
  11168. this._doNotHandleContextLost = false;
  11169. // FPS
  11170. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11171. this._fps = 60;
  11172. this._deltaTime = 0;
  11173. /**
  11174. * Turn this value on if you want to pause FPS computation when in background
  11175. */
  11176. this.disablePerformanceMonitorInBackground = false;
  11177. // States
  11178. /** @ignore */
  11179. this._depthCullingState = new BABYLON._DepthCullingState();
  11180. /** @ignore */
  11181. this._stencilState = new BABYLON._StencilState();
  11182. /** @ignore */
  11183. this._alphaState = new BABYLON._AlphaState();
  11184. /** @ignore */
  11185. this._alphaMode = Engine.ALPHA_DISABLE;
  11186. // Cache
  11187. this._internalTexturesCache = new Array();
  11188. /** @ignore */
  11189. this._activeChannel = 0;
  11190. this._currentTextureChannel = -1;
  11191. /** @ignore */
  11192. this._boundTexturesCache = {};
  11193. this._compiledEffects = {};
  11194. this._vertexAttribArraysEnabled = [];
  11195. this._uintIndicesCurrentlySet = false;
  11196. this._currentBoundBuffer = new Array();
  11197. this._currentBufferPointers = new Array();
  11198. this._currentInstanceLocations = new Array();
  11199. this._currentInstanceBuffers = new Array();
  11200. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11201. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11202. this._vaoRecordInProgress = false;
  11203. this._mustWipeVertexAttributes = false;
  11204. this._nextFreeTextureSlots = new Array();
  11205. this._maxSimultaneousTextures = 0;
  11206. this._activeRequests = new Array();
  11207. // Hardware supported Compressed Textures
  11208. this._texturesSupported = new Array();
  11209. this._onVRFullScreenTriggered = function () {
  11210. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11211. //get the old size before we change
  11212. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11213. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11214. //get the width and height, change the render size
  11215. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11216. _this.setHardwareScalingLevel(1);
  11217. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11218. }
  11219. else {
  11220. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11221. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11222. }
  11223. };
  11224. this._boundUniforms = {};
  11225. // Register promises
  11226. BABYLON.PromisePolyfill.Apply();
  11227. var canvas = null;
  11228. Engine.Instances.push(this);
  11229. if (!canvasOrContext) {
  11230. return;
  11231. }
  11232. options = options || {};
  11233. if (canvasOrContext.getContext) {
  11234. canvas = canvasOrContext;
  11235. this._renderingCanvas = canvas;
  11236. if (antialias != null) {
  11237. options.antialias = antialias;
  11238. }
  11239. if (options.deterministicLockstep === undefined) {
  11240. options.deterministicLockstep = false;
  11241. }
  11242. if (options.lockstepMaxSteps === undefined) {
  11243. options.lockstepMaxSteps = 4;
  11244. }
  11245. if (options.preserveDrawingBuffer === undefined) {
  11246. options.preserveDrawingBuffer = false;
  11247. }
  11248. if (options.audioEngine === undefined) {
  11249. options.audioEngine = true;
  11250. }
  11251. if (options.stencil === undefined) {
  11252. options.stencil = true;
  11253. }
  11254. this._deterministicLockstep = options.deterministicLockstep;
  11255. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11256. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11257. // Exceptions
  11258. if (navigator && navigator.userAgent) {
  11259. var ua = navigator.userAgent;
  11260. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11261. var exception = _a[_i];
  11262. var key = exception.key;
  11263. var targets = exception.targets;
  11264. if (ua.indexOf(key) > -1) {
  11265. if (exception.capture && exception.captureConstraint) {
  11266. var capture = exception.capture;
  11267. var constraint = exception.captureConstraint;
  11268. var regex = new RegExp(capture);
  11269. var matches = regex.exec(ua);
  11270. if (matches && matches.length > 0) {
  11271. var capturedValue = parseInt(matches[matches.length - 1]);
  11272. if (capturedValue >= constraint) {
  11273. continue;
  11274. }
  11275. }
  11276. }
  11277. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11278. var target = targets_1[_b];
  11279. switch (target) {
  11280. case "uniformBuffer":
  11281. this.disableUniformBuffers = true;
  11282. break;
  11283. case "textureBindingOptimization":
  11284. this.disableTextureBindingOptimization = true;
  11285. break;
  11286. }
  11287. }
  11288. }
  11289. }
  11290. }
  11291. // GL
  11292. if (!options.disableWebGL2Support) {
  11293. try {
  11294. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11295. if (this._gl) {
  11296. this._webGLVersion = 2.0;
  11297. }
  11298. }
  11299. catch (e) {
  11300. // Do nothing
  11301. }
  11302. }
  11303. if (!this._gl) {
  11304. if (!canvas) {
  11305. throw new Error("The provided canvas is null or undefined.");
  11306. }
  11307. try {
  11308. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11309. }
  11310. catch (e) {
  11311. throw new Error("WebGL not supported");
  11312. }
  11313. }
  11314. if (!this._gl) {
  11315. throw new Error("WebGL not supported");
  11316. }
  11317. this._onCanvasFocus = function () {
  11318. _this.onCanvasFocusObservable.notifyObservers(_this);
  11319. };
  11320. this._onCanvasBlur = function () {
  11321. _this.onCanvasBlurObservable.notifyObservers(_this);
  11322. };
  11323. canvas.addEventListener("focus", this._onCanvasFocus);
  11324. canvas.addEventListener("blur", this._onCanvasBlur);
  11325. this._onBlur = function () {
  11326. if (_this.disablePerformanceMonitorInBackground) {
  11327. _this._performanceMonitor.disable();
  11328. }
  11329. _this._windowIsBackground = true;
  11330. };
  11331. this._onFocus = function () {
  11332. if (_this.disablePerformanceMonitorInBackground) {
  11333. _this._performanceMonitor.enable();
  11334. }
  11335. _this._windowIsBackground = false;
  11336. };
  11337. this._onCanvasPointerOut = function (ev) {
  11338. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11339. };
  11340. window.addEventListener("blur", this._onBlur);
  11341. window.addEventListener("focus", this._onFocus);
  11342. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11343. // Context lost
  11344. if (!this._doNotHandleContextLost) {
  11345. this._onContextLost = function (evt) {
  11346. evt.preventDefault();
  11347. _this._contextWasLost = true;
  11348. BABYLON.Tools.Warn("WebGL context lost.");
  11349. _this.onContextLostObservable.notifyObservers(_this);
  11350. };
  11351. this._onContextRestored = function (evt) {
  11352. // Adding a timeout to avoid race condition at browser level
  11353. setTimeout(function () {
  11354. // Rebuild gl context
  11355. _this._initGLContext();
  11356. // Rebuild effects
  11357. _this._rebuildEffects();
  11358. // Rebuild textures
  11359. _this._rebuildInternalTextures();
  11360. // Rebuild buffers
  11361. _this._rebuildBuffers();
  11362. // Cache
  11363. _this.wipeCaches(true);
  11364. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11365. _this.onContextRestoredObservable.notifyObservers(_this);
  11366. _this._contextWasLost = false;
  11367. }, 0);
  11368. };
  11369. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11370. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11371. }
  11372. }
  11373. else {
  11374. this._gl = canvasOrContext;
  11375. this._renderingCanvas = this._gl.canvas;
  11376. if (this._gl.renderbufferStorageMultisample) {
  11377. this._webGLVersion = 2.0;
  11378. }
  11379. options.stencil = this._gl.getContextAttributes().stencil;
  11380. }
  11381. // Viewport
  11382. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11383. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11384. this.resize();
  11385. this._isStencilEnable = options.stencil ? true : false;
  11386. this._initGLContext();
  11387. if (canvas) {
  11388. // Fullscreen
  11389. this._onFullscreenChange = function () {
  11390. if (document.fullscreen !== undefined) {
  11391. _this.isFullscreen = document.fullscreen;
  11392. }
  11393. else if (document.mozFullScreen !== undefined) {
  11394. _this.isFullscreen = document.mozFullScreen;
  11395. }
  11396. else if (document.webkitIsFullScreen !== undefined) {
  11397. _this.isFullscreen = document.webkitIsFullScreen;
  11398. }
  11399. else if (document.msIsFullScreen !== undefined) {
  11400. _this.isFullscreen = document.msIsFullScreen;
  11401. }
  11402. // Pointer lock
  11403. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11404. canvas.requestPointerLock = canvas.requestPointerLock ||
  11405. canvas.msRequestPointerLock ||
  11406. canvas.mozRequestPointerLock ||
  11407. canvas.webkitRequestPointerLock;
  11408. if (canvas.requestPointerLock) {
  11409. canvas.requestPointerLock();
  11410. }
  11411. }
  11412. };
  11413. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11414. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11415. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11416. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11417. // Pointer lock
  11418. this._onPointerLockChange = function () {
  11419. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11420. document.webkitPointerLockElement === canvas ||
  11421. document.msPointerLockElement === canvas ||
  11422. document.pointerLockElement === canvas);
  11423. };
  11424. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11425. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11426. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11427. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11428. this._onVRDisplayPointerRestricted = function () {
  11429. if (canvas) {
  11430. canvas.requestPointerLock();
  11431. }
  11432. };
  11433. this._onVRDisplayPointerUnrestricted = function () {
  11434. document.exitPointerLock();
  11435. };
  11436. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11437. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11438. }
  11439. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11440. Engine.audioEngine = new BABYLON.AudioEngine();
  11441. }
  11442. // Prepare buffer pointers
  11443. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11444. this._currentBufferPointers[i] = new BufferPointer();
  11445. }
  11446. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11447. // Load WebVR Devices
  11448. if (options.autoEnableWebVR) {
  11449. this.initWebVR();
  11450. }
  11451. // Detect if we are running on a faulty buggy OS.
  11452. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11453. // Detect if we are running on a faulty buggy desktop OS.
  11454. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11455. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11456. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11457. }
  11458. Object.defineProperty(Engine, "LastCreatedEngine", {
  11459. /**
  11460. * Gets the latest created engine
  11461. */
  11462. get: function () {
  11463. if (Engine.Instances.length === 0) {
  11464. return null;
  11465. }
  11466. return Engine.Instances[Engine.Instances.length - 1];
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(Engine, "LastCreatedScene", {
  11472. /**
  11473. * Gets the latest created scene
  11474. */
  11475. get: function () {
  11476. var lastCreatedEngine = Engine.LastCreatedEngine;
  11477. if (!lastCreatedEngine) {
  11478. return null;
  11479. }
  11480. if (lastCreatedEngine.scenes.length === 0) {
  11481. return null;
  11482. }
  11483. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11484. },
  11485. enumerable: true,
  11486. configurable: true
  11487. });
  11488. /**
  11489. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11490. * @param flag defines which part of the materials must be marked as dirty
  11491. * @param predicate defines a predicate used to filter which materials should be affected
  11492. */
  11493. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11494. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11495. var engine = Engine.Instances[engineIndex];
  11496. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11497. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11498. }
  11499. }
  11500. };
  11501. Object.defineProperty(Engine, "NEVER", {
  11502. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11503. get: function () {
  11504. return Engine._NEVER;
  11505. },
  11506. enumerable: true,
  11507. configurable: true
  11508. });
  11509. Object.defineProperty(Engine, "ALWAYS", {
  11510. /** 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 */
  11511. get: function () {
  11512. return Engine._ALWAYS;
  11513. },
  11514. enumerable: true,
  11515. configurable: true
  11516. });
  11517. Object.defineProperty(Engine, "LESS", {
  11518. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11519. get: function () {
  11520. return Engine._LESS;
  11521. },
  11522. enumerable: true,
  11523. configurable: true
  11524. });
  11525. Object.defineProperty(Engine, "EQUAL", {
  11526. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11527. get: function () {
  11528. return Engine._EQUAL;
  11529. },
  11530. enumerable: true,
  11531. configurable: true
  11532. });
  11533. Object.defineProperty(Engine, "LEQUAL", {
  11534. /** 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 */
  11535. get: function () {
  11536. return Engine._LEQUAL;
  11537. },
  11538. enumerable: true,
  11539. configurable: true
  11540. });
  11541. Object.defineProperty(Engine, "GREATER", {
  11542. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11543. get: function () {
  11544. return Engine._GREATER;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(Engine, "GEQUAL", {
  11550. /** 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 */
  11551. get: function () {
  11552. return Engine._GEQUAL;
  11553. },
  11554. enumerable: true,
  11555. configurable: true
  11556. });
  11557. Object.defineProperty(Engine, "NOTEQUAL", {
  11558. /** 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 */
  11559. get: function () {
  11560. return Engine._NOTEQUAL;
  11561. },
  11562. enumerable: true,
  11563. configurable: true
  11564. });
  11565. Object.defineProperty(Engine, "KEEP", {
  11566. /** Passed to stencilOperation to specify that stencil value must be kept */
  11567. get: function () {
  11568. return Engine._KEEP;
  11569. },
  11570. enumerable: true,
  11571. configurable: true
  11572. });
  11573. Object.defineProperty(Engine, "REPLACE", {
  11574. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11575. get: function () {
  11576. return Engine._REPLACE;
  11577. },
  11578. enumerable: true,
  11579. configurable: true
  11580. });
  11581. Object.defineProperty(Engine, "INCR", {
  11582. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11583. get: function () {
  11584. return Engine._INCR;
  11585. },
  11586. enumerable: true,
  11587. configurable: true
  11588. });
  11589. Object.defineProperty(Engine, "DECR", {
  11590. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11591. get: function () {
  11592. return Engine._DECR;
  11593. },
  11594. enumerable: true,
  11595. configurable: true
  11596. });
  11597. Object.defineProperty(Engine, "INVERT", {
  11598. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11599. get: function () {
  11600. return Engine._INVERT;
  11601. },
  11602. enumerable: true,
  11603. configurable: true
  11604. });
  11605. Object.defineProperty(Engine, "INCR_WRAP", {
  11606. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11607. get: function () {
  11608. return Engine._INCR_WRAP;
  11609. },
  11610. enumerable: true,
  11611. configurable: true
  11612. });
  11613. Object.defineProperty(Engine, "DECR_WRAP", {
  11614. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11615. get: function () {
  11616. return Engine._DECR_WRAP;
  11617. },
  11618. enumerable: true,
  11619. configurable: true
  11620. });
  11621. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11622. // Alpha
  11623. /** Defines that alpha blending is disabled */
  11624. get: function () {
  11625. return Engine._ALPHA_DISABLE;
  11626. },
  11627. enumerable: true,
  11628. configurable: true
  11629. });
  11630. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11631. /** Defines that alpha blending to SRC + DEST */
  11632. get: function () {
  11633. return Engine._ALPHA_ONEONE;
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. Object.defineProperty(Engine, "ALPHA_ADD", {
  11639. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11640. get: function () {
  11641. return Engine._ALPHA_ADD;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11647. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11648. get: function () {
  11649. return Engine._ALPHA_COMBINE;
  11650. },
  11651. enumerable: true,
  11652. configurable: true
  11653. });
  11654. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11655. /** Defines that alpha blending to DEST - SRC * DEST */
  11656. get: function () {
  11657. return Engine._ALPHA_SUBTRACT;
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11663. /** Defines that alpha blending to SRC * DEST */
  11664. get: function () {
  11665. return Engine._ALPHA_MULTIPLY;
  11666. },
  11667. enumerable: true,
  11668. configurable: true
  11669. });
  11670. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11671. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11672. get: function () {
  11673. return Engine._ALPHA_MAXIMIZED;
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11679. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11680. get: function () {
  11681. return Engine._ALPHA_PREMULTIPLIED;
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11687. /**
  11688. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11689. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11690. */
  11691. get: function () {
  11692. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11693. },
  11694. enumerable: true,
  11695. configurable: true
  11696. });
  11697. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11698. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11699. get: function () {
  11700. return Engine._ALPHA_INTERPOLATE;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11706. /**
  11707. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11708. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11709. */
  11710. get: function () {
  11711. return Engine._ALPHA_SCREENMODE;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11717. // Delays
  11718. /** Defines that the ressource is not delayed*/
  11719. get: function () {
  11720. return Engine._DELAYLOADSTATE_NONE;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11726. /** Defines that the ressource was successfully delay loaded */
  11727. get: function () {
  11728. return Engine._DELAYLOADSTATE_LOADED;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11734. /** Defines that the ressource is currently delay loading */
  11735. get: function () {
  11736. return Engine._DELAYLOADSTATE_LOADING;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11742. /** Defines that the ressource is delayed and has not started loading */
  11743. get: function () {
  11744. return Engine._DELAYLOADSTATE_NOTLOADED;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11750. /** ALPHA */
  11751. get: function () {
  11752. return Engine._TEXTUREFORMAT_ALPHA;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11758. /** LUMINANCE */
  11759. get: function () {
  11760. return Engine._TEXTUREFORMAT_LUMINANCE;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11766. /**
  11767. * R32F
  11768. */
  11769. get: function () {
  11770. return Engine._TEXTUREFORMAT_R32F;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11776. /**
  11777. * RG32F
  11778. */
  11779. get: function () {
  11780. return Engine._TEXTUREFORMAT_RG32F;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11786. /**
  11787. * RGB32F
  11788. */
  11789. get: function () {
  11790. return Engine._TEXTUREFORMAT_RGB32F;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11796. /**
  11797. * RGBA32F
  11798. */
  11799. get: function () {
  11800. return Engine._TEXTUREFORMAT_RGBA32F;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11806. /** LUMINANCE_ALPHA */
  11807. get: function () {
  11808. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11814. /** RGB */
  11815. get: function () {
  11816. return Engine._TEXTUREFORMAT_RGB;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11822. /** RGBA */
  11823. get: function () {
  11824. return Engine._TEXTUREFORMAT_RGBA;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11830. /** UNSIGNED_INT */
  11831. get: function () {
  11832. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11838. /** FLOAT */
  11839. get: function () {
  11840. return Engine._TEXTURETYPE_FLOAT;
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11846. /** HALF_FLOAT */
  11847. get: function () {
  11848. return Engine._TEXTURETYPE_HALF_FLOAT;
  11849. },
  11850. enumerable: true,
  11851. configurable: true
  11852. });
  11853. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11854. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11855. get: function () {
  11856. return Engine._SCALEMODE_FLOOR;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11862. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11863. get: function () {
  11864. return Engine._SCALEMODE_NEAREST;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11870. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11871. get: function () {
  11872. return Engine._SCALEMODE_CEILING;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Object.defineProperty(Engine, "Version", {
  11878. /**
  11879. * Returns the current version of the framework
  11880. */
  11881. get: function () {
  11882. return "3.2.0-beta.4";
  11883. },
  11884. enumerable: true,
  11885. configurable: true
  11886. });
  11887. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11888. /**
  11889. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11890. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11891. */
  11892. get: function () {
  11893. return this._vrExclusivePointerMode;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11899. /**
  11900. * Gets a boolean indicating that the engine supports uniform buffers
  11901. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11902. */
  11903. get: function () {
  11904. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11910. /**
  11911. * Gets a boolean indicating that only power of 2 textures are supported
  11912. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11913. */
  11914. get: function () {
  11915. return this._webGLVersion < 2 || this.forcePOTTextures;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11921. /**
  11922. * Gets the performance monitor attached to this engine
  11923. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11924. */
  11925. get: function () {
  11926. return this._performanceMonitor;
  11927. },
  11928. enumerable: true,
  11929. configurable: true
  11930. });
  11931. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11932. /**
  11933. * Gets the list of texture formats supported
  11934. */
  11935. get: function () {
  11936. return this._texturesSupported;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11942. /**
  11943. * Gets the list of texture formats in use
  11944. */
  11945. get: function () {
  11946. return this._textureFormatInUse;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine.prototype, "currentViewport", {
  11952. /**
  11953. * Gets the current viewport
  11954. */
  11955. get: function () {
  11956. return this._cachedViewport;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11962. /**
  11963. * Gets the default empty texture
  11964. */
  11965. get: function () {
  11966. if (!this._emptyTexture) {
  11967. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11968. }
  11969. return this._emptyTexture;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11975. /**
  11976. * Gets the default empty 3D texture
  11977. */
  11978. get: function () {
  11979. if (!this._emptyTexture3D) {
  11980. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11981. }
  11982. return this._emptyTexture3D;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11988. /**
  11989. * Gets the default empty cube texture
  11990. */
  11991. get: function () {
  11992. if (!this._emptyCubeTexture) {
  11993. var faceData = new Uint8Array(4);
  11994. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11995. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11996. }
  11997. return this._emptyCubeTexture;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Engine.prototype._rebuildInternalTextures = function () {
  12003. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12004. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12005. var internalTexture = currentState_1[_i];
  12006. internalTexture._rebuild();
  12007. }
  12008. };
  12009. Engine.prototype._rebuildEffects = function () {
  12010. for (var key in this._compiledEffects) {
  12011. var effect = this._compiledEffects[key];
  12012. effect._prepareEffect();
  12013. }
  12014. BABYLON.Effect.ResetCache();
  12015. };
  12016. Engine.prototype._rebuildBuffers = function () {
  12017. // Index / Vertex
  12018. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12019. var scene = _a[_i];
  12020. scene.resetCachedMaterial();
  12021. scene._rebuildGeometries();
  12022. scene._rebuildTextures();
  12023. }
  12024. // Uniforms
  12025. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12026. var uniformBuffer = _c[_b];
  12027. uniformBuffer._rebuild();
  12028. }
  12029. };
  12030. Engine.prototype._initGLContext = function () {
  12031. // Caps
  12032. this._caps = new EngineCapabilities();
  12033. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12034. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12035. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12036. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12037. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12038. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12039. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12040. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12041. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12042. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12043. // Infos
  12044. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12045. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12046. if (rendererInfo != null) {
  12047. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12048. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12049. }
  12050. if (!this._glVendor) {
  12051. this._glVendor = "Unknown vendor";
  12052. }
  12053. if (!this._glRenderer) {
  12054. this._glRenderer = "Unknown renderer";
  12055. }
  12056. // Constants
  12057. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12058. if (this._gl.RGBA16F !== 0x881A) {
  12059. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12060. }
  12061. if (this._gl.RGBA32F !== 0x8814) {
  12062. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12063. }
  12064. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12065. this._gl.DEPTH24_STENCIL8 = 35056;
  12066. }
  12067. // Extensions
  12068. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12069. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12070. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12071. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12072. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12073. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12074. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12075. 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');
  12076. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12077. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12078. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12079. this._caps.highPrecisionShaderSupported = true;
  12080. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12081. if (this._caps.timerQuery) {
  12082. if (this._webGLVersion === 1) {
  12083. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12084. }
  12085. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12086. }
  12087. // Checks if some of the format renders first to allow the use of webgl inspector.
  12088. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12089. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12090. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12091. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12092. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12093. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12094. if (this._webGLVersion > 1) {
  12095. this._gl.HALF_FLOAT_OES = 0x140B;
  12096. }
  12097. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12098. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12099. // Draw buffers
  12100. if (this._webGLVersion > 1) {
  12101. this._caps.drawBuffersExtension = true;
  12102. }
  12103. else {
  12104. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12105. if (drawBuffersExtension !== null) {
  12106. this._caps.drawBuffersExtension = true;
  12107. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12108. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12109. for (var i = 0; i < 16; i++) {
  12110. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12111. }
  12112. }
  12113. else {
  12114. this._caps.drawBuffersExtension = false;
  12115. }
  12116. }
  12117. // Depth Texture
  12118. if (this._webGLVersion > 1) {
  12119. this._caps.depthTextureExtension = true;
  12120. }
  12121. else {
  12122. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12123. if (depthTextureExtension != null) {
  12124. this._caps.depthTextureExtension = true;
  12125. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12126. }
  12127. }
  12128. // Vertex array object
  12129. if (this._webGLVersion > 1) {
  12130. this._caps.vertexArrayObject = true;
  12131. }
  12132. else {
  12133. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12134. if (vertexArrayObjectExtension != null) {
  12135. this._caps.vertexArrayObject = true;
  12136. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12137. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12138. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12139. }
  12140. else {
  12141. this._caps.vertexArrayObject = false;
  12142. }
  12143. }
  12144. // Instances count
  12145. if (this._webGLVersion > 1) {
  12146. this._caps.instancedArrays = true;
  12147. }
  12148. else {
  12149. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12150. if (instanceExtension != null) {
  12151. this._caps.instancedArrays = true;
  12152. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12153. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12154. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12155. }
  12156. else {
  12157. this._caps.instancedArrays = false;
  12158. }
  12159. }
  12160. // Intelligently add supported compressed formats in order to check for.
  12161. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12162. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12163. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12164. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12165. if (this._caps.astc)
  12166. this.texturesSupported.push('-astc.ktx');
  12167. if (this._caps.s3tc)
  12168. this.texturesSupported.push('-dxt.ktx');
  12169. if (this._caps.pvrtc)
  12170. this.texturesSupported.push('-pvrtc.ktx');
  12171. if (this._caps.etc2)
  12172. this.texturesSupported.push('-etc2.ktx');
  12173. if (this._caps.etc1)
  12174. this.texturesSupported.push('-etc1.ktx');
  12175. if (this._gl.getShaderPrecisionFormat) {
  12176. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12177. if (highp) {
  12178. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12179. }
  12180. }
  12181. // Depth buffer
  12182. this.setDepthBuffer(true);
  12183. this.setDepthFunctionToLessOrEqual();
  12184. this.setDepthWrite(true);
  12185. // Texture maps
  12186. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12187. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12188. this._nextFreeTextureSlots.push(slot);
  12189. }
  12190. };
  12191. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12192. /**
  12193. * Gets version of the current webGL context
  12194. */
  12195. get: function () {
  12196. return this._webGLVersion;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12202. /**
  12203. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12204. */
  12205. get: function () {
  12206. return this._isStencilEnable;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Engine.prototype._prepareWorkingCanvas = function () {
  12212. if (this._workingCanvas) {
  12213. return;
  12214. }
  12215. this._workingCanvas = document.createElement("canvas");
  12216. var context = this._workingCanvas.getContext("2d");
  12217. if (context) {
  12218. this._workingContext = context;
  12219. }
  12220. };
  12221. /**
  12222. * Reset the texture cache to empty state
  12223. */
  12224. Engine.prototype.resetTextureCache = function () {
  12225. for (var key in this._boundTexturesCache) {
  12226. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12227. continue;
  12228. }
  12229. var boundTexture = this._boundTexturesCache[key];
  12230. if (boundTexture) {
  12231. this._removeDesignatedSlot(boundTexture);
  12232. }
  12233. this._boundTexturesCache[key] = null;
  12234. }
  12235. if (!this.disableTextureBindingOptimization) {
  12236. this._nextFreeTextureSlots = [];
  12237. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12238. this._nextFreeTextureSlots.push(slot);
  12239. }
  12240. }
  12241. this._currentTextureChannel = -1;
  12242. };
  12243. /**
  12244. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12245. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12246. * @returns true if engine is in deterministic lock step mode
  12247. */
  12248. Engine.prototype.isDeterministicLockStep = function () {
  12249. return this._deterministicLockstep;
  12250. };
  12251. /**
  12252. * Gets the max steps when engine is running in deterministic lock step
  12253. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12254. * @returns the max steps
  12255. */
  12256. Engine.prototype.getLockstepMaxSteps = function () {
  12257. return this._lockstepMaxSteps;
  12258. };
  12259. /**
  12260. * Gets an object containing information about the current webGL context
  12261. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12262. */
  12263. Engine.prototype.getGlInfo = function () {
  12264. return {
  12265. vendor: this._glVendor,
  12266. renderer: this._glRenderer,
  12267. version: this._glVersion
  12268. };
  12269. };
  12270. /**
  12271. * Gets current aspect ratio
  12272. * @param camera defines the camera to use to get the aspect ratio
  12273. * @param useScreen defines if screen size must be used (or the current render target if any)
  12274. * @returns a number defining the aspect ratio
  12275. */
  12276. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12277. if (useScreen === void 0) { useScreen = false; }
  12278. var viewport = camera.viewport;
  12279. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12280. };
  12281. /**
  12282. * Gets the current render width
  12283. * @param useScreen defines if screen size must be used (or the current render target if any)
  12284. * @returns a number defining the current render width
  12285. */
  12286. Engine.prototype.getRenderWidth = function (useScreen) {
  12287. if (useScreen === void 0) { useScreen = false; }
  12288. if (!useScreen && this._currentRenderTarget) {
  12289. return this._currentRenderTarget.width;
  12290. }
  12291. return this._gl.drawingBufferWidth;
  12292. };
  12293. /**
  12294. * Gets the current render height
  12295. * @param useScreen defines if screen size must be used (or the current render target if any)
  12296. * @returns a number defining the current render height
  12297. */
  12298. Engine.prototype.getRenderHeight = function (useScreen) {
  12299. if (useScreen === void 0) { useScreen = false; }
  12300. if (!useScreen && this._currentRenderTarget) {
  12301. return this._currentRenderTarget.height;
  12302. }
  12303. return this._gl.drawingBufferHeight;
  12304. };
  12305. /**
  12306. * Gets the HTML canvas attached with the current webGL context
  12307. * @returns a HTML canvas
  12308. */
  12309. Engine.prototype.getRenderingCanvas = function () {
  12310. return this._renderingCanvas;
  12311. };
  12312. /**
  12313. * Gets the client rect of the HTML canvas attached with the current webGL context
  12314. * @returns a client rectanglee
  12315. */
  12316. Engine.prototype.getRenderingCanvasClientRect = function () {
  12317. if (!this._renderingCanvas) {
  12318. return null;
  12319. }
  12320. return this._renderingCanvas.getBoundingClientRect();
  12321. };
  12322. /**
  12323. * Defines the hardware scaling level.
  12324. * By default the hardware scaling level is computed from the window device ratio.
  12325. * 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.
  12326. * @param level defines the level to use
  12327. */
  12328. Engine.prototype.setHardwareScalingLevel = function (level) {
  12329. this._hardwareScalingLevel = level;
  12330. this.resize();
  12331. };
  12332. /**
  12333. * Gets the current hardware scaling level.
  12334. * By default the hardware scaling level is computed from the window device ratio.
  12335. * 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.
  12336. * @returns a number indicating the current hardware scaling level
  12337. */
  12338. Engine.prototype.getHardwareScalingLevel = function () {
  12339. return this._hardwareScalingLevel;
  12340. };
  12341. /**
  12342. * Gets the list of loaded textures
  12343. * @returns an array containing all loaded textures
  12344. */
  12345. Engine.prototype.getLoadedTexturesCache = function () {
  12346. return this._internalTexturesCache;
  12347. };
  12348. /**
  12349. * Gets the object containing all engine capabilities
  12350. * @returns the EngineCapabilities object
  12351. */
  12352. Engine.prototype.getCaps = function () {
  12353. return this._caps;
  12354. };
  12355. Object.defineProperty(Engine.prototype, "drawCalls", {
  12356. /** @ignore */
  12357. get: function () {
  12358. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12359. return 0;
  12360. },
  12361. enumerable: true,
  12362. configurable: true
  12363. });
  12364. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12365. /** @ignore */
  12366. get: function () {
  12367. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12368. return null;
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. /**
  12374. * Gets the current depth function
  12375. * @returns a number defining the depth function
  12376. */
  12377. Engine.prototype.getDepthFunction = function () {
  12378. return this._depthCullingState.depthFunc;
  12379. };
  12380. /**
  12381. * Sets the current depth function
  12382. * @param depthFunc defines the function to use
  12383. */
  12384. Engine.prototype.setDepthFunction = function (depthFunc) {
  12385. this._depthCullingState.depthFunc = depthFunc;
  12386. };
  12387. /**
  12388. * Sets the current depth function to GREATER
  12389. */
  12390. Engine.prototype.setDepthFunctionToGreater = function () {
  12391. this._depthCullingState.depthFunc = this._gl.GREATER;
  12392. };
  12393. /**
  12394. * Sets the current depth function to GEQUAL
  12395. */
  12396. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12397. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12398. };
  12399. /**
  12400. * Sets the current depth function to LESS
  12401. */
  12402. Engine.prototype.setDepthFunctionToLess = function () {
  12403. this._depthCullingState.depthFunc = this._gl.LESS;
  12404. };
  12405. /**
  12406. * Sets the current depth function to LEQUAL
  12407. */
  12408. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12409. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12410. };
  12411. /**
  12412. * Gets a boolean indicating if stencil buffer is enabled
  12413. * @returns the current stencil buffer state
  12414. */
  12415. Engine.prototype.getStencilBuffer = function () {
  12416. return this._stencilState.stencilTest;
  12417. };
  12418. /**
  12419. * Enable or disable the stencil buffer
  12420. * @param enable defines if the stencil buffer must be enabled or disabled
  12421. */
  12422. Engine.prototype.setStencilBuffer = function (enable) {
  12423. this._stencilState.stencilTest = enable;
  12424. };
  12425. /**
  12426. * Gets the current stencil mask
  12427. * @returns a number defining the new stencil mask to use
  12428. */
  12429. Engine.prototype.getStencilMask = function () {
  12430. return this._stencilState.stencilMask;
  12431. };
  12432. /**
  12433. * Sets the current stencil mask
  12434. * @param mask defines the new stencil mask to use
  12435. */
  12436. Engine.prototype.setStencilMask = function (mask) {
  12437. this._stencilState.stencilMask = mask;
  12438. };
  12439. /**
  12440. * Gets the current stencil function
  12441. * @returns a number defining the stencil function to use
  12442. */
  12443. Engine.prototype.getStencilFunction = function () {
  12444. return this._stencilState.stencilFunc;
  12445. };
  12446. /**
  12447. * Gets the current stencil reference value
  12448. * @returns a number defining the stencil reference value to use
  12449. */
  12450. Engine.prototype.getStencilFunctionReference = function () {
  12451. return this._stencilState.stencilFuncRef;
  12452. };
  12453. /**
  12454. * Gets the current stencil mask
  12455. * @returns a number defining the stencil mask to use
  12456. */
  12457. Engine.prototype.getStencilFunctionMask = function () {
  12458. return this._stencilState.stencilFuncMask;
  12459. };
  12460. /**
  12461. * Sets the current stencil function
  12462. * @param stencilFunc defines the new stencil function to use
  12463. */
  12464. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12465. this._stencilState.stencilFunc = stencilFunc;
  12466. };
  12467. /**
  12468. * Sets the current stencil reference
  12469. * @param reference defines the new stencil reference to use
  12470. */
  12471. Engine.prototype.setStencilFunctionReference = function (reference) {
  12472. this._stencilState.stencilFuncRef = reference;
  12473. };
  12474. /**
  12475. * Sets the current stencil mask
  12476. * @param mask defines the new stencil mask to use
  12477. */
  12478. Engine.prototype.setStencilFunctionMask = function (mask) {
  12479. this._stencilState.stencilFuncMask = mask;
  12480. };
  12481. /**
  12482. * Gets the current stencil operation when stencil fails
  12483. * @returns a number defining stencil operation to use when stencil fails
  12484. */
  12485. Engine.prototype.getStencilOperationFail = function () {
  12486. return this._stencilState.stencilOpStencilFail;
  12487. };
  12488. /**
  12489. * Gets the current stencil operation when depth fails
  12490. * @returns a number defining stencil operation to use when depth fails
  12491. */
  12492. Engine.prototype.getStencilOperationDepthFail = function () {
  12493. return this._stencilState.stencilOpDepthFail;
  12494. };
  12495. /**
  12496. * Gets the current stencil operation when stencil passes
  12497. * @returns a number defining stencil operation to use when stencil passes
  12498. */
  12499. Engine.prototype.getStencilOperationPass = function () {
  12500. return this._stencilState.stencilOpStencilDepthPass;
  12501. };
  12502. /**
  12503. * Sets the stencil operation to use when stencil fails
  12504. * @param operation defines the stencil operation to use when stencil fails
  12505. */
  12506. Engine.prototype.setStencilOperationFail = function (operation) {
  12507. this._stencilState.stencilOpStencilFail = operation;
  12508. };
  12509. /**
  12510. * Sets the stencil operation to use when depth fails
  12511. * @param operation defines the stencil operation to use when depth fails
  12512. */
  12513. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12514. this._stencilState.stencilOpDepthFail = operation;
  12515. };
  12516. /**
  12517. * Sets the stencil operation to use when stencil passes
  12518. * @param operation defines the stencil operation to use when stencil passes
  12519. */
  12520. Engine.prototype.setStencilOperationPass = function (operation) {
  12521. this._stencilState.stencilOpStencilDepthPass = operation;
  12522. };
  12523. /**
  12524. * Sets a boolean indicating if the dithering state is enabled or disabled
  12525. * @param value defines the dithering state
  12526. */
  12527. Engine.prototype.setDitheringState = function (value) {
  12528. if (value) {
  12529. this._gl.enable(this._gl.DITHER);
  12530. }
  12531. else {
  12532. this._gl.disable(this._gl.DITHER);
  12533. }
  12534. };
  12535. /**
  12536. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12537. * @param value defines the rasterizer state
  12538. */
  12539. Engine.prototype.setRasterizerState = function (value) {
  12540. if (value) {
  12541. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12542. }
  12543. else {
  12544. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12545. }
  12546. };
  12547. /**
  12548. * stop executing a render loop function and remove it from the execution array
  12549. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12550. */
  12551. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12552. if (!renderFunction) {
  12553. this._activeRenderLoops = [];
  12554. return;
  12555. }
  12556. var index = this._activeRenderLoops.indexOf(renderFunction);
  12557. if (index >= 0) {
  12558. this._activeRenderLoops.splice(index, 1);
  12559. }
  12560. };
  12561. /** @ignore */
  12562. Engine.prototype._renderLoop = function () {
  12563. if (!this._contextWasLost) {
  12564. var shouldRender = true;
  12565. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12566. shouldRender = false;
  12567. }
  12568. if (shouldRender) {
  12569. // Start new frame
  12570. this.beginFrame();
  12571. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12572. var renderFunction = this._activeRenderLoops[index];
  12573. renderFunction();
  12574. }
  12575. // Present
  12576. this.endFrame();
  12577. }
  12578. }
  12579. if (this._activeRenderLoops.length > 0) {
  12580. // Register new frame
  12581. var requester = null;
  12582. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12583. requester = this._vrDisplay;
  12584. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12585. }
  12586. else {
  12587. this._renderingQueueLaunched = false;
  12588. }
  12589. };
  12590. /**
  12591. * Register and execute a render loop. The engine can have more than one render function
  12592. * @param renderFunction defines the function to continuously execute
  12593. */
  12594. Engine.prototype.runRenderLoop = function (renderFunction) {
  12595. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12596. return;
  12597. }
  12598. this._activeRenderLoops.push(renderFunction);
  12599. if (!this._renderingQueueLaunched) {
  12600. this._renderingQueueLaunched = true;
  12601. this._bindedRenderFunction = this._renderLoop.bind(this);
  12602. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12603. }
  12604. };
  12605. /**
  12606. * Toggle full screen mode
  12607. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12608. * @param options defines an option object to be sent to the requestFullscreen function
  12609. */
  12610. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12611. if (this.isFullscreen) {
  12612. BABYLON.Tools.ExitFullscreen();
  12613. }
  12614. else {
  12615. this._pointerLockRequested = requestPointerLock;
  12616. if (this._renderingCanvas) {
  12617. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12618. }
  12619. }
  12620. };
  12621. /**
  12622. * Clear the current render buffer or the current render target (if any is set up)
  12623. * @param color defines the color to use
  12624. * @param backBuffer defines if the back buffer must be cleared
  12625. * @param depth defines if the depth buffer must be cleared
  12626. * @param stencil defines if the stencil buffer must be cleared
  12627. */
  12628. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12629. if (stencil === void 0) { stencil = false; }
  12630. this.applyStates();
  12631. var mode = 0;
  12632. if (backBuffer && color) {
  12633. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12634. mode |= this._gl.COLOR_BUFFER_BIT;
  12635. }
  12636. if (depth) {
  12637. this._gl.clearDepth(1.0);
  12638. mode |= this._gl.DEPTH_BUFFER_BIT;
  12639. }
  12640. if (stencil) {
  12641. this._gl.clearStencil(0);
  12642. mode |= this._gl.STENCIL_BUFFER_BIT;
  12643. }
  12644. this._gl.clear(mode);
  12645. };
  12646. /**
  12647. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12648. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12649. * @param y defines the y-coordinate of the corner of the clear rectangle
  12650. * @param width defines the width of the clear rectangle
  12651. * @param height defines the height of the clear rectangle
  12652. * @param clearColor defines the clear color
  12653. */
  12654. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12655. var gl = this._gl;
  12656. // Save state
  12657. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12658. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12659. // Change state
  12660. gl.enable(gl.SCISSOR_TEST);
  12661. gl.scissor(x, y, width, height);
  12662. // Clear
  12663. this.clear(clearColor, true, true, true);
  12664. // Restore state
  12665. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12666. if (curScissor === true) {
  12667. gl.enable(gl.SCISSOR_TEST);
  12668. }
  12669. else {
  12670. gl.disable(gl.SCISSOR_TEST);
  12671. }
  12672. };
  12673. /**
  12674. * Set the WebGL's viewport
  12675. * @param viewport defines the viewport element to be used
  12676. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12677. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12678. */
  12679. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12680. var width = requiredWidth || this.getRenderWidth();
  12681. var height = requiredHeight || this.getRenderHeight();
  12682. var x = viewport.x || 0;
  12683. var y = viewport.y || 0;
  12684. this._cachedViewport = viewport;
  12685. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12686. };
  12687. /**
  12688. * Directly set the WebGL Viewport
  12689. * @param x defines the x coordinate of the viewport (in screen space)
  12690. * @param y defines the y coordinate of the viewport (in screen space)
  12691. * @param width defines the width of the viewport (in screen space)
  12692. * @param height defines the height of the viewport (in screen space)
  12693. * @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
  12694. */
  12695. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12696. var currentViewport = this._cachedViewport;
  12697. this._cachedViewport = null;
  12698. this._gl.viewport(x, y, width, height);
  12699. return currentViewport;
  12700. };
  12701. /**
  12702. * Begin a new frame
  12703. */
  12704. Engine.prototype.beginFrame = function () {
  12705. this.onBeginFrameObservable.notifyObservers(this);
  12706. this._measureFps();
  12707. };
  12708. /**
  12709. * Enf the current frame
  12710. */
  12711. Engine.prototype.endFrame = function () {
  12712. // Force a flush in case we are using a bad OS.
  12713. if (this._badOS) {
  12714. this.flushFramebuffer();
  12715. }
  12716. // Submit frame to the vr device, if enabled
  12717. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12718. // TODO: We should only submit the frame if we read frameData successfully.
  12719. this._vrDisplay.submitFrame();
  12720. }
  12721. this.onEndFrameObservable.notifyObservers(this);
  12722. };
  12723. /**
  12724. * Resize the view according to the canvas' size
  12725. */
  12726. Engine.prototype.resize = function () {
  12727. // We're not resizing the size of the canvas while in VR mode & presenting
  12728. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12729. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12730. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12731. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12732. }
  12733. };
  12734. /**
  12735. * Force a specific size of the canvas
  12736. * @param width defines the new canvas' width
  12737. * @param height defines the new canvas' height
  12738. */
  12739. Engine.prototype.setSize = function (width, height) {
  12740. if (!this._renderingCanvas) {
  12741. return;
  12742. }
  12743. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12744. return;
  12745. }
  12746. this._renderingCanvas.width = width;
  12747. this._renderingCanvas.height = height;
  12748. for (var index = 0; index < this.scenes.length; index++) {
  12749. var scene = this.scenes[index];
  12750. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12751. var cam = scene.cameras[camIndex];
  12752. cam._currentRenderId = 0;
  12753. }
  12754. }
  12755. if (this.onResizeObservable.hasObservers) {
  12756. this.onResizeObservable.notifyObservers(this);
  12757. }
  12758. };
  12759. // WebVR functions
  12760. /**
  12761. * Gets a boolean indicating if a webVR device was detected
  12762. * @returns true if a webVR device was detected
  12763. */
  12764. Engine.prototype.isVRDevicePresent = function () {
  12765. return !!this._vrDisplay;
  12766. };
  12767. /**
  12768. * Gets the current webVR device
  12769. * @returns the current webVR device (or null)
  12770. */
  12771. Engine.prototype.getVRDevice = function () {
  12772. return this._vrDisplay;
  12773. };
  12774. /**
  12775. * Initializes a webVR display and starts listening to display change events
  12776. * The onVRDisplayChangedObservable will be notified upon these changes
  12777. * @returns The onVRDisplayChangedObservable
  12778. */
  12779. Engine.prototype.initWebVR = function () {
  12780. this.initWebVRAsync();
  12781. return this.onVRDisplayChangedObservable;
  12782. };
  12783. /**
  12784. * Initializes a webVR display and starts listening to display change events
  12785. * The onVRDisplayChangedObservable will be notified upon these changes
  12786. * @returns A promise containing a VRDisplay and if vr is supported
  12787. */
  12788. Engine.prototype.initWebVRAsync = function () {
  12789. var _this = this;
  12790. var notifyObservers = function () {
  12791. var eventArgs = {
  12792. vrDisplay: _this._vrDisplay,
  12793. vrSupported: _this._vrSupported
  12794. };
  12795. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12796. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12797. };
  12798. if (!this._onVrDisplayConnect) {
  12799. this._onVrDisplayConnect = function (event) {
  12800. _this._vrDisplay = event.display;
  12801. notifyObservers();
  12802. };
  12803. this._onVrDisplayDisconnect = function () {
  12804. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12805. _this._vrDisplay = undefined;
  12806. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12807. notifyObservers();
  12808. };
  12809. this._onVrDisplayPresentChange = function () {
  12810. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12811. };
  12812. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12813. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12814. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12815. }
  12816. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12817. this._webVRInitPromise.then(notifyObservers);
  12818. return this._webVRInitPromise;
  12819. };
  12820. /**
  12821. * Call this function to switch to webVR mode
  12822. * Will do nothing if webVR is not supported or if there is no webVR device
  12823. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12824. */
  12825. Engine.prototype.enableVR = function () {
  12826. var _this = this;
  12827. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12828. var onResolved = function () {
  12829. _this.onVRRequestPresentComplete.notifyObservers(true);
  12830. _this._onVRFullScreenTriggered();
  12831. };
  12832. var onRejected = function () {
  12833. _this.onVRRequestPresentComplete.notifyObservers(false);
  12834. };
  12835. this.onVRRequestPresentStart.notifyObservers(this);
  12836. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12837. }
  12838. };
  12839. /**
  12840. * Call this function to leave webVR mode
  12841. * Will do nothing if webVR is not supported or if there is no webVR device
  12842. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12843. */
  12844. Engine.prototype.disableVR = function () {
  12845. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12846. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12847. }
  12848. };
  12849. Engine.prototype._getVRDisplaysAsync = function () {
  12850. var _this = this;
  12851. return new Promise(function (res, rej) {
  12852. if (navigator.getVRDisplays) {
  12853. navigator.getVRDisplays().then(function (devices) {
  12854. _this._vrSupported = true;
  12855. // note that devices may actually be an empty array. This is fine;
  12856. // we expect this._vrDisplay to be undefined in this case.
  12857. _this._vrDisplay = devices[0];
  12858. res({
  12859. vrDisplay: _this._vrDisplay,
  12860. vrSupported: _this._vrSupported
  12861. });
  12862. });
  12863. }
  12864. else {
  12865. _this._vrDisplay = undefined;
  12866. _this._vrSupported = false;
  12867. res({
  12868. vrDisplay: _this._vrDisplay,
  12869. vrSupported: _this._vrSupported
  12870. });
  12871. }
  12872. });
  12873. };
  12874. /**
  12875. * Binds the frame buffer to the specified texture.
  12876. * @param texture The texture to render to or null for the default canvas
  12877. * @param faceIndex The face of the texture to render to in case of cube texture
  12878. * @param requiredWidth The width of the target to render to
  12879. * @param requiredHeight The height of the target to render to
  12880. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12881. * @param depthStencilTexture The depth stencil texture to use to render
  12882. */
  12883. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12884. if (this._currentRenderTarget) {
  12885. this.unBindFramebuffer(this._currentRenderTarget);
  12886. }
  12887. this._currentRenderTarget = texture;
  12888. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12889. var gl = this._gl;
  12890. if (texture.isCube) {
  12891. if (faceIndex === undefined) {
  12892. faceIndex = 0;
  12893. }
  12894. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12895. if (depthStencilTexture) {
  12896. if (depthStencilTexture._generateStencilBuffer) {
  12897. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12898. }
  12899. else {
  12900. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12901. }
  12902. }
  12903. }
  12904. if (this._cachedViewport && !forceFullscreenViewport) {
  12905. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12906. }
  12907. else {
  12908. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12909. }
  12910. this.wipeCaches();
  12911. };
  12912. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12913. if (this._currentFramebuffer !== framebuffer) {
  12914. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12915. this._currentFramebuffer = framebuffer;
  12916. }
  12917. };
  12918. /**
  12919. * Unbind the current render target texture from the webGL context
  12920. * @param texture defines the render target texture to unbind
  12921. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12922. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12923. */
  12924. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12925. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12926. this._currentRenderTarget = null;
  12927. // If MSAA, we need to bitblt back to main texture
  12928. var gl = this._gl;
  12929. if (texture._MSAAFramebuffer) {
  12930. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12931. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12932. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12933. }
  12934. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12935. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12936. gl.generateMipmap(gl.TEXTURE_2D);
  12937. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12938. }
  12939. if (onBeforeUnbind) {
  12940. if (texture._MSAAFramebuffer) {
  12941. // Bind the correct framebuffer
  12942. this.bindUnboundFramebuffer(texture._framebuffer);
  12943. }
  12944. onBeforeUnbind();
  12945. }
  12946. this.bindUnboundFramebuffer(null);
  12947. };
  12948. /**
  12949. * Unbind a list of render target textures from the webGL context
  12950. * This is used only when drawBuffer extension or webGL2 are active
  12951. * @param textures defines the render target textures to unbind
  12952. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12953. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12954. */
  12955. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12956. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12957. this._currentRenderTarget = null;
  12958. // If MSAA, we need to bitblt back to main texture
  12959. var gl = this._gl;
  12960. if (textures[0]._MSAAFramebuffer) {
  12961. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12962. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12963. var attachments = textures[0]._attachments;
  12964. if (!attachments) {
  12965. attachments = new Array(textures.length);
  12966. textures[0]._attachments = attachments;
  12967. }
  12968. for (var i = 0; i < textures.length; i++) {
  12969. var texture = textures[i];
  12970. for (var j = 0; j < attachments.length; j++) {
  12971. attachments[j] = gl.NONE;
  12972. }
  12973. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12974. gl.readBuffer(attachments[i]);
  12975. gl.drawBuffers(attachments);
  12976. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12977. }
  12978. for (var i = 0; i < attachments.length; i++) {
  12979. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12980. }
  12981. gl.drawBuffers(attachments);
  12982. }
  12983. for (var i = 0; i < textures.length; i++) {
  12984. var texture = textures[i];
  12985. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12986. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12987. gl.generateMipmap(gl.TEXTURE_2D);
  12988. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12989. }
  12990. }
  12991. if (onBeforeUnbind) {
  12992. if (textures[0]._MSAAFramebuffer) {
  12993. // Bind the correct framebuffer
  12994. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12995. }
  12996. onBeforeUnbind();
  12997. }
  12998. this.bindUnboundFramebuffer(null);
  12999. };
  13000. /**
  13001. * Force the mipmap generation for the given render target texture
  13002. * @param texture defines the render target texture to use
  13003. */
  13004. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13005. if (texture.generateMipMaps) {
  13006. var gl = this._gl;
  13007. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13008. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13010. }
  13011. };
  13012. /**
  13013. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13014. */
  13015. Engine.prototype.flushFramebuffer = function () {
  13016. this._gl.flush();
  13017. };
  13018. /**
  13019. * Unbind the current render target and bind the default framebuffer
  13020. */
  13021. Engine.prototype.restoreDefaultFramebuffer = function () {
  13022. if (this._currentRenderTarget) {
  13023. this.unBindFramebuffer(this._currentRenderTarget);
  13024. }
  13025. else {
  13026. this.bindUnboundFramebuffer(null);
  13027. }
  13028. if (this._cachedViewport) {
  13029. this.setViewport(this._cachedViewport);
  13030. }
  13031. this.wipeCaches();
  13032. };
  13033. // UBOs
  13034. /**
  13035. * Create an uniform buffer
  13036. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13037. * @param elements defines the content of the uniform buffer
  13038. * @returns the webGL uniform buffer
  13039. */
  13040. Engine.prototype.createUniformBuffer = function (elements) {
  13041. var ubo = this._gl.createBuffer();
  13042. if (!ubo) {
  13043. throw new Error("Unable to create uniform buffer");
  13044. }
  13045. this.bindUniformBuffer(ubo);
  13046. if (elements instanceof Float32Array) {
  13047. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13048. }
  13049. else {
  13050. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13051. }
  13052. this.bindUniformBuffer(null);
  13053. ubo.references = 1;
  13054. return ubo;
  13055. };
  13056. /**
  13057. * Create a dynamic uniform buffer
  13058. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13059. * @param elements defines the content of the uniform buffer
  13060. * @returns the webGL uniform buffer
  13061. */
  13062. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13063. var ubo = this._gl.createBuffer();
  13064. if (!ubo) {
  13065. throw new Error("Unable to create dynamic uniform buffer");
  13066. }
  13067. this.bindUniformBuffer(ubo);
  13068. if (elements instanceof Float32Array) {
  13069. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13070. }
  13071. else {
  13072. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13073. }
  13074. this.bindUniformBuffer(null);
  13075. ubo.references = 1;
  13076. return ubo;
  13077. };
  13078. /**
  13079. * Update an existing uniform buffer
  13080. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13081. * @param uniformBuffer defines the target uniform buffer
  13082. * @param elements defines the content to update
  13083. * @param offset defines the offset in the uniform buffer where update should start
  13084. * @param count defines the size of the data to update
  13085. */
  13086. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13087. this.bindUniformBuffer(uniformBuffer);
  13088. if (offset === undefined) {
  13089. offset = 0;
  13090. }
  13091. if (count === undefined) {
  13092. if (elements instanceof Float32Array) {
  13093. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13094. }
  13095. else {
  13096. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13097. }
  13098. }
  13099. else {
  13100. if (elements instanceof Float32Array) {
  13101. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13102. }
  13103. else {
  13104. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13105. }
  13106. }
  13107. this.bindUniformBuffer(null);
  13108. };
  13109. // VBOs
  13110. Engine.prototype._resetVertexBufferBinding = function () {
  13111. this.bindArrayBuffer(null);
  13112. this._cachedVertexBuffers = null;
  13113. };
  13114. /**
  13115. * Creates a vertex buffer
  13116. * @param data the data for the vertex buffer
  13117. * @returns the new WebGL static buffer
  13118. */
  13119. Engine.prototype.createVertexBuffer = function (data) {
  13120. var vbo = this._gl.createBuffer();
  13121. if (!vbo) {
  13122. throw new Error("Unable to create vertex buffer");
  13123. }
  13124. this.bindArrayBuffer(vbo);
  13125. if (data instanceof Array) {
  13126. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13127. }
  13128. else {
  13129. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13130. }
  13131. this._resetVertexBufferBinding();
  13132. vbo.references = 1;
  13133. return vbo;
  13134. };
  13135. /**
  13136. * Creates a dynamic vertex buffer
  13137. * @param data the data for the dynamic vertex buffer
  13138. * @returns the new WebGL dynamic buffer
  13139. */
  13140. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13141. var vbo = this._gl.createBuffer();
  13142. if (!vbo) {
  13143. throw new Error("Unable to create dynamic vertex buffer");
  13144. }
  13145. this.bindArrayBuffer(vbo);
  13146. if (data instanceof Array) {
  13147. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13148. }
  13149. else {
  13150. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13151. }
  13152. this._resetVertexBufferBinding();
  13153. vbo.references = 1;
  13154. return vbo;
  13155. };
  13156. /**
  13157. * Update a dynamic index buffer
  13158. * @param indexBuffer defines the target index buffer
  13159. * @param indices defines the data to update
  13160. * @param offset defines the offset in the target index buffer where update should start
  13161. */
  13162. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13163. if (offset === void 0) { offset = 0; }
  13164. // Force cache update
  13165. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13166. this.bindIndexBuffer(indexBuffer);
  13167. var arrayBuffer;
  13168. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13169. arrayBuffer = indices;
  13170. }
  13171. else {
  13172. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13173. }
  13174. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13175. this._resetIndexBufferBinding();
  13176. };
  13177. /**
  13178. * Updates a dynamic vertex buffer.
  13179. * @param vertexBuffer the vertex buffer to update
  13180. * @param data the data used to update the vertex buffer
  13181. * @param byteOffset the byte offset of the data
  13182. * @param byteLength the byte length of the data
  13183. */
  13184. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13185. this.bindArrayBuffer(vertexBuffer);
  13186. if (byteOffset === undefined) {
  13187. byteOffset = 0;
  13188. }
  13189. if (byteLength === undefined) {
  13190. if (data instanceof Array) {
  13191. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13192. }
  13193. else {
  13194. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13195. }
  13196. }
  13197. else {
  13198. if (data instanceof Array) {
  13199. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13200. }
  13201. else {
  13202. if (data instanceof ArrayBuffer) {
  13203. data = new Uint8Array(data, byteOffset, byteLength);
  13204. }
  13205. else {
  13206. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13207. }
  13208. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13209. }
  13210. }
  13211. this._resetVertexBufferBinding();
  13212. };
  13213. Engine.prototype._resetIndexBufferBinding = function () {
  13214. this.bindIndexBuffer(null);
  13215. this._cachedIndexBuffer = null;
  13216. };
  13217. /**
  13218. * Creates a new index buffer
  13219. * @param indices defines the content of the index buffer
  13220. * @param updatable defines if the index buffer must be updatable
  13221. * @returns a new webGL buffer
  13222. */
  13223. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13224. var vbo = this._gl.createBuffer();
  13225. if (!vbo) {
  13226. throw new Error("Unable to create index buffer");
  13227. }
  13228. this.bindIndexBuffer(vbo);
  13229. // Check for 32 bits indices
  13230. var arrayBuffer;
  13231. var need32Bits = false;
  13232. if (indices instanceof Uint16Array) {
  13233. arrayBuffer = indices;
  13234. }
  13235. else {
  13236. //check 32 bit support
  13237. if (this._caps.uintIndices) {
  13238. if (indices instanceof Uint32Array) {
  13239. arrayBuffer = indices;
  13240. need32Bits = true;
  13241. }
  13242. else {
  13243. //number[] or Int32Array, check if 32 bit is necessary
  13244. for (var index = 0; index < indices.length; index++) {
  13245. if (indices[index] > 65535) {
  13246. need32Bits = true;
  13247. break;
  13248. }
  13249. }
  13250. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13251. }
  13252. }
  13253. else {
  13254. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13255. arrayBuffer = new Uint16Array(indices);
  13256. }
  13257. }
  13258. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13259. this._resetIndexBufferBinding();
  13260. vbo.references = 1;
  13261. vbo.is32Bits = need32Bits;
  13262. return vbo;
  13263. };
  13264. /**
  13265. * Bind a webGL buffer to the webGL context
  13266. * @param buffer defines the buffer to bind
  13267. */
  13268. Engine.prototype.bindArrayBuffer = function (buffer) {
  13269. if (!this._vaoRecordInProgress) {
  13270. this._unbindVertexArrayObject();
  13271. }
  13272. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13273. };
  13274. /**
  13275. * Bind an uniform buffer to the current webGL context
  13276. * @param buffer defines the buffer to bind
  13277. */
  13278. Engine.prototype.bindUniformBuffer = function (buffer) {
  13279. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13280. };
  13281. /**
  13282. * Bind a buffer to the current webGL context at a given location
  13283. * @param buffer defines the buffer to bind
  13284. * @param location defines the index where to bind the buffer
  13285. */
  13286. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13287. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13288. };
  13289. /**
  13290. * Bind a specific block at a given index in a specific shader program
  13291. * @param shaderProgram defines the shader program
  13292. * @param blockName defines the block name
  13293. * @param index defines the index where to bind the block
  13294. */
  13295. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13296. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13297. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13298. };
  13299. ;
  13300. Engine.prototype.bindIndexBuffer = function (buffer) {
  13301. if (!this._vaoRecordInProgress) {
  13302. this._unbindVertexArrayObject();
  13303. }
  13304. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13305. };
  13306. Engine.prototype.bindBuffer = function (buffer, target) {
  13307. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13308. this._gl.bindBuffer(target, buffer);
  13309. this._currentBoundBuffer[target] = buffer;
  13310. }
  13311. };
  13312. /**
  13313. * update the bound buffer with the given data
  13314. * @param data defines the data to update
  13315. */
  13316. Engine.prototype.updateArrayBuffer = function (data) {
  13317. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13318. };
  13319. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13320. var pointer = this._currentBufferPointers[indx];
  13321. var changed = false;
  13322. if (!pointer.active) {
  13323. changed = true;
  13324. pointer.active = true;
  13325. pointer.index = indx;
  13326. pointer.size = size;
  13327. pointer.type = type;
  13328. pointer.normalized = normalized;
  13329. pointer.stride = stride;
  13330. pointer.offset = offset;
  13331. pointer.buffer = buffer;
  13332. }
  13333. else {
  13334. if (pointer.buffer !== buffer) {
  13335. pointer.buffer = buffer;
  13336. changed = true;
  13337. }
  13338. if (pointer.size !== size) {
  13339. pointer.size = size;
  13340. changed = true;
  13341. }
  13342. if (pointer.type !== type) {
  13343. pointer.type = type;
  13344. changed = true;
  13345. }
  13346. if (pointer.normalized !== normalized) {
  13347. pointer.normalized = normalized;
  13348. changed = true;
  13349. }
  13350. if (pointer.stride !== stride) {
  13351. pointer.stride = stride;
  13352. changed = true;
  13353. }
  13354. if (pointer.offset !== offset) {
  13355. pointer.offset = offset;
  13356. changed = true;
  13357. }
  13358. }
  13359. if (changed || this._vaoRecordInProgress) {
  13360. this.bindArrayBuffer(buffer);
  13361. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13362. }
  13363. };
  13364. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13365. if (indexBuffer == null) {
  13366. return;
  13367. }
  13368. if (this._cachedIndexBuffer !== indexBuffer) {
  13369. this._cachedIndexBuffer = indexBuffer;
  13370. this.bindIndexBuffer(indexBuffer);
  13371. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13372. }
  13373. };
  13374. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13375. var attributes = effect.getAttributesNames();
  13376. if (!this._vaoRecordInProgress) {
  13377. this._unbindVertexArrayObject();
  13378. }
  13379. this.unbindAllAttributes();
  13380. for (var index = 0; index < attributes.length; index++) {
  13381. var order = effect.getAttributeLocation(index);
  13382. if (order >= 0) {
  13383. var vertexBuffer = vertexBuffers[attributes[index]];
  13384. if (!vertexBuffer) {
  13385. continue;
  13386. }
  13387. this._gl.enableVertexAttribArray(order);
  13388. if (!this._vaoRecordInProgress) {
  13389. this._vertexAttribArraysEnabled[order] = true;
  13390. }
  13391. var buffer = vertexBuffer.getBuffer();
  13392. if (buffer) {
  13393. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13394. if (vertexBuffer.getIsInstanced()) {
  13395. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13396. if (!this._vaoRecordInProgress) {
  13397. this._currentInstanceLocations.push(order);
  13398. this._currentInstanceBuffers.push(buffer);
  13399. }
  13400. }
  13401. }
  13402. }
  13403. }
  13404. };
  13405. /**
  13406. * Records a vertex array object
  13407. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13408. * @param vertexBuffers defines the list of vertex buffers to store
  13409. * @param indexBuffer defines the index buffer to store
  13410. * @param effect defines the effect to store
  13411. * @returns the new vertex array object
  13412. */
  13413. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13414. var vao = this._gl.createVertexArray();
  13415. this._vaoRecordInProgress = true;
  13416. this._gl.bindVertexArray(vao);
  13417. this._mustWipeVertexAttributes = true;
  13418. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13419. this.bindIndexBuffer(indexBuffer);
  13420. this._vaoRecordInProgress = false;
  13421. this._gl.bindVertexArray(null);
  13422. return vao;
  13423. };
  13424. /**
  13425. * Bind a specific vertex array object
  13426. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13427. * @param vertexArrayObject defines the vertex array object to bind
  13428. * @param indexBuffer defines the index buffer to bind
  13429. */
  13430. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13431. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13432. this._cachedVertexArrayObject = vertexArrayObject;
  13433. this._gl.bindVertexArray(vertexArrayObject);
  13434. this._cachedVertexBuffers = null;
  13435. this._cachedIndexBuffer = null;
  13436. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13437. this._mustWipeVertexAttributes = true;
  13438. }
  13439. };
  13440. /**
  13441. * Bind webGl buffers directly to the webGL context
  13442. * @param vertexBuffer defines the vertex buffer to bind
  13443. * @param indexBuffer defines the index buffer to bind
  13444. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13445. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13446. * @param effect defines the effect associated with the vertex buffer
  13447. */
  13448. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13449. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13450. this._cachedVertexBuffers = vertexBuffer;
  13451. this._cachedEffectForVertexBuffers = effect;
  13452. var attributesCount = effect.getAttributesCount();
  13453. this._unbindVertexArrayObject();
  13454. this.unbindAllAttributes();
  13455. var offset = 0;
  13456. for (var index = 0; index < attributesCount; index++) {
  13457. if (index < vertexDeclaration.length) {
  13458. var order = effect.getAttributeLocation(index);
  13459. if (order >= 0) {
  13460. this._gl.enableVertexAttribArray(order);
  13461. this._vertexAttribArraysEnabled[order] = true;
  13462. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13463. }
  13464. offset += vertexDeclaration[index] * 4;
  13465. }
  13466. }
  13467. }
  13468. this._bindIndexBufferWithCache(indexBuffer);
  13469. };
  13470. Engine.prototype._unbindVertexArrayObject = function () {
  13471. if (!this._cachedVertexArrayObject) {
  13472. return;
  13473. }
  13474. this._cachedVertexArrayObject = null;
  13475. this._gl.bindVertexArray(null);
  13476. };
  13477. /**
  13478. * Bind a list of vertex buffers to the webGL context
  13479. * @param vertexBuffers defines the list of vertex buffers to bind
  13480. * @param indexBuffer defines the index buffer to bind
  13481. * @param effect defines the effect associated with the vertex buffers
  13482. */
  13483. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13484. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13485. this._cachedVertexBuffers = vertexBuffers;
  13486. this._cachedEffectForVertexBuffers = effect;
  13487. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13488. }
  13489. this._bindIndexBufferWithCache(indexBuffer);
  13490. };
  13491. /**
  13492. * Unbind all instance attributes
  13493. */
  13494. Engine.prototype.unbindInstanceAttributes = function () {
  13495. var boundBuffer;
  13496. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13497. var instancesBuffer = this._currentInstanceBuffers[i];
  13498. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13499. boundBuffer = instancesBuffer;
  13500. this.bindArrayBuffer(instancesBuffer);
  13501. }
  13502. var offsetLocation = this._currentInstanceLocations[i];
  13503. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13504. }
  13505. this._currentInstanceBuffers.length = 0;
  13506. this._currentInstanceLocations.length = 0;
  13507. };
  13508. /**
  13509. * Release and free the memory of a vertex array object
  13510. * @param vao defines the vertex array object to delete
  13511. */
  13512. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13513. this._gl.deleteVertexArray(vao);
  13514. };
  13515. /** @ignore */
  13516. Engine.prototype._releaseBuffer = function (buffer) {
  13517. buffer.references--;
  13518. if (buffer.references === 0) {
  13519. this._gl.deleteBuffer(buffer);
  13520. return true;
  13521. }
  13522. return false;
  13523. };
  13524. /**
  13525. * Creates a webGL buffer to use with instanciation
  13526. * @param capacity defines the size of the buffer
  13527. * @returns the webGL buffer
  13528. */
  13529. Engine.prototype.createInstancesBuffer = function (capacity) {
  13530. var buffer = this._gl.createBuffer();
  13531. if (!buffer) {
  13532. throw new Error("Unable to create instance buffer");
  13533. }
  13534. buffer.capacity = capacity;
  13535. this.bindArrayBuffer(buffer);
  13536. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13537. return buffer;
  13538. };
  13539. /**
  13540. * Delete a webGL buffer used with instanciation
  13541. * @param buffer defines the webGL buffer to delete
  13542. */
  13543. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13544. this._gl.deleteBuffer(buffer);
  13545. };
  13546. /**
  13547. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13548. * @param instancesBuffer defines the webGL buffer to update and bind
  13549. * @param data defines the data to store in the buffer
  13550. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13551. */
  13552. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13553. this.bindArrayBuffer(instancesBuffer);
  13554. if (data) {
  13555. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13556. }
  13557. if (offsetLocations[0].index !== undefined) {
  13558. var stride = 0;
  13559. for (var i = 0; i < offsetLocations.length; i++) {
  13560. var ai = offsetLocations[i];
  13561. stride += ai.attributeSize * 4;
  13562. }
  13563. for (var i = 0; i < offsetLocations.length; i++) {
  13564. var ai = offsetLocations[i];
  13565. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13566. this._gl.enableVertexAttribArray(ai.index);
  13567. this._vertexAttribArraysEnabled[ai.index] = true;
  13568. }
  13569. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13570. this._gl.vertexAttribDivisor(ai.index, 1);
  13571. this._currentInstanceLocations.push(ai.index);
  13572. this._currentInstanceBuffers.push(instancesBuffer);
  13573. }
  13574. }
  13575. else {
  13576. for (var index = 0; index < 4; index++) {
  13577. var offsetLocation = offsetLocations[index];
  13578. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13579. this._gl.enableVertexAttribArray(offsetLocation);
  13580. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13581. }
  13582. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13583. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13584. this._currentInstanceLocations.push(offsetLocation);
  13585. this._currentInstanceBuffers.push(instancesBuffer);
  13586. }
  13587. }
  13588. };
  13589. /**
  13590. * Apply all cached states (depth, culling, stencil and alpha)
  13591. */
  13592. Engine.prototype.applyStates = function () {
  13593. this._depthCullingState.apply(this._gl);
  13594. this._stencilState.apply(this._gl);
  13595. this._alphaState.apply(this._gl);
  13596. };
  13597. /**
  13598. * Send a draw order
  13599. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13600. * @param indexStart defines the starting index
  13601. * @param indexCount defines the number of index to draw
  13602. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13603. */
  13604. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13605. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13606. };
  13607. /**
  13608. * Draw a list of points
  13609. * @param verticesStart defines the index of first vertex to draw
  13610. * @param verticesCount defines the count of vertices to draw
  13611. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13612. */
  13613. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13614. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13615. };
  13616. /**
  13617. * Draw a list of unindexed primitives
  13618. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13619. * @param verticesStart defines the index of first vertex to draw
  13620. * @param verticesCount defines the count of vertices to draw
  13621. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13622. */
  13623. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13624. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13625. };
  13626. /**
  13627. * Draw a list of indexed primitives
  13628. * @param fillMode defines the primitive to use
  13629. * @param indexStart defines the starting index
  13630. * @param indexCount defines the number of index to draw
  13631. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13632. */
  13633. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13634. // Apply states
  13635. this.applyStates();
  13636. this._drawCalls.addCount(1, false);
  13637. // Render
  13638. var drawMode = this._drawMode(fillMode);
  13639. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13640. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13641. if (instancesCount) {
  13642. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13643. }
  13644. else {
  13645. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13646. }
  13647. };
  13648. /**
  13649. * Draw a list of unindexed primitives
  13650. * @param fillMode defines the primitive to use
  13651. * @param verticesStart defines the index of first vertex to draw
  13652. * @param verticesCount defines the count of vertices to draw
  13653. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13654. */
  13655. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13656. // Apply states
  13657. this.applyStates();
  13658. this._drawCalls.addCount(1, false);
  13659. var drawMode = this._drawMode(fillMode);
  13660. if (instancesCount) {
  13661. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13662. }
  13663. else {
  13664. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13665. }
  13666. };
  13667. Engine.prototype._drawMode = function (fillMode) {
  13668. switch (fillMode) {
  13669. // Triangle views
  13670. case BABYLON.Material.TriangleFillMode:
  13671. return this._gl.TRIANGLES;
  13672. case BABYLON.Material.PointFillMode:
  13673. return this._gl.POINTS;
  13674. case BABYLON.Material.WireFrameFillMode:
  13675. return this._gl.LINES;
  13676. // Draw modes
  13677. case BABYLON.Material.PointListDrawMode:
  13678. return this._gl.POINTS;
  13679. case BABYLON.Material.LineListDrawMode:
  13680. return this._gl.LINES;
  13681. case BABYLON.Material.LineLoopDrawMode:
  13682. return this._gl.LINE_LOOP;
  13683. case BABYLON.Material.LineStripDrawMode:
  13684. return this._gl.LINE_STRIP;
  13685. case BABYLON.Material.TriangleStripDrawMode:
  13686. return this._gl.TRIANGLE_STRIP;
  13687. case BABYLON.Material.TriangleFanDrawMode:
  13688. return this._gl.TRIANGLE_FAN;
  13689. default:
  13690. return this._gl.TRIANGLES;
  13691. }
  13692. };
  13693. // Shaders
  13694. /** @ignore */
  13695. Engine.prototype._releaseEffect = function (effect) {
  13696. if (this._compiledEffects[effect._key]) {
  13697. delete this._compiledEffects[effect._key];
  13698. this._deleteProgram(effect.getProgram());
  13699. }
  13700. };
  13701. /** @ignore */
  13702. Engine.prototype._deleteProgram = function (program) {
  13703. if (program) {
  13704. program.__SPECTOR_rebuildProgram = null;
  13705. if (program.transformFeedback) {
  13706. this.deleteTransformFeedback(program.transformFeedback);
  13707. program.transformFeedback = null;
  13708. }
  13709. this._gl.deleteProgram(program);
  13710. }
  13711. };
  13712. /**
  13713. * Create a new effect (used to store vertex/fragment shaders)
  13714. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13715. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13716. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13717. * @param samplers defines an array of string used to represent textures
  13718. * @param defines defines the string containing the defines to use to compile the shaders
  13719. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13720. * @param onCompiled defines a function to call when the effect creation is successful
  13721. * @param onError defines a function to call when the effect creation has failed
  13722. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13723. * @returns the new Effect
  13724. */
  13725. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13726. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13727. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13728. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13729. if (this._compiledEffects[name]) {
  13730. var compiledEffect = this._compiledEffects[name];
  13731. if (onCompiled && compiledEffect.isReady()) {
  13732. onCompiled(compiledEffect);
  13733. }
  13734. return compiledEffect;
  13735. }
  13736. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13737. effect._key = name;
  13738. this._compiledEffects[name] = effect;
  13739. return effect;
  13740. };
  13741. /**
  13742. * Create an effect to use with particle systems
  13743. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13744. * @param uniformsNames defines a list of attribute names
  13745. * @param samplers defines an array of string used to represent textures
  13746. * @param defines defines the string containing the defines to use to compile the shaders
  13747. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13748. * @param onCompiled defines a function to call when the effect creation is successful
  13749. * @param onError defines a function to call when the effect creation has failed
  13750. * @returns the new Effect
  13751. */
  13752. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13753. if (uniformsNames === void 0) { uniformsNames = []; }
  13754. if (samplers === void 0) { samplers = []; }
  13755. if (defines === void 0) { defines = ""; }
  13756. return this.createEffect({
  13757. vertex: "particles",
  13758. fragmentElement: fragmentName
  13759. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13760. };
  13761. /**
  13762. * Directly creates a webGL program
  13763. * @param vertexCode defines the vertex shader code to use
  13764. * @param fragmentCode defines the fragment shader code to use
  13765. * @param context defines the webGL context to use (if not set, the current one will be used)
  13766. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13767. * @returns the new webGL program
  13768. */
  13769. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13770. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13771. context = context || this._gl;
  13772. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13773. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13774. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13775. };
  13776. /**
  13777. * Creates a webGL program
  13778. * @param vertexCode defines the vertex shader code to use
  13779. * @param fragmentCode defines the fragment shader code to use
  13780. * @param defines defines the string containing the defines to use to compile the shaders
  13781. * @param context defines the webGL context to use (if not set, the current one will be used)
  13782. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13783. * @returns the new webGL program
  13784. */
  13785. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13786. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13787. context = context || this._gl;
  13788. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13789. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13790. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13791. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13792. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13793. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13794. return program;
  13795. };
  13796. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13797. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13798. var shaderProgram = context.createProgram();
  13799. if (!shaderProgram) {
  13800. throw new Error("Unable to create program");
  13801. }
  13802. context.attachShader(shaderProgram, vertexShader);
  13803. context.attachShader(shaderProgram, fragmentShader);
  13804. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13805. var transformFeedback = this.createTransformFeedback();
  13806. this.bindTransformFeedback(transformFeedback);
  13807. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13808. shaderProgram.transformFeedback = transformFeedback;
  13809. }
  13810. context.linkProgram(shaderProgram);
  13811. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13812. this.bindTransformFeedback(null);
  13813. }
  13814. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13815. if (!linked) {
  13816. context.validateProgram(shaderProgram);
  13817. var error = context.getProgramInfoLog(shaderProgram);
  13818. if (error) {
  13819. throw new Error(error);
  13820. }
  13821. }
  13822. context.deleteShader(vertexShader);
  13823. context.deleteShader(fragmentShader);
  13824. return shaderProgram;
  13825. };
  13826. /**
  13827. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13828. * @param shaderProgram defines the webGL program to use
  13829. * @param uniformsNames defines the list of uniform names
  13830. * @returns an array of webGL uniform locations
  13831. */
  13832. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13833. var results = new Array();
  13834. for (var index = 0; index < uniformsNames.length; index++) {
  13835. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13836. }
  13837. return results;
  13838. };
  13839. /**
  13840. * Gets the lsit of active attributes for a given webGL program
  13841. * @param shaderProgram defines the webGL program to use
  13842. * @param attributesNames defines the list of attribute names to get
  13843. * @returns an array of indices indicating the offset of each attribute
  13844. */
  13845. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13846. var results = [];
  13847. for (var index = 0; index < attributesNames.length; index++) {
  13848. try {
  13849. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13850. }
  13851. catch (e) {
  13852. results.push(-1);
  13853. }
  13854. }
  13855. return results;
  13856. };
  13857. /**
  13858. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13859. * @param effect defines the effect to activate
  13860. */
  13861. Engine.prototype.enableEffect = function (effect) {
  13862. if (!effect) {
  13863. return;
  13864. }
  13865. // Use program
  13866. this.bindSamplers(effect);
  13867. this._currentEffect = effect;
  13868. if (effect.onBind) {
  13869. effect.onBind(effect);
  13870. }
  13871. effect.onBindObservable.notifyObservers(effect);
  13872. };
  13873. /**
  13874. * Set the value of an uniform to an array of int32
  13875. * @param uniform defines the webGL uniform location where to store the value
  13876. * @param array defines the array of int32 to store
  13877. */
  13878. Engine.prototype.setIntArray = function (uniform, array) {
  13879. if (!uniform)
  13880. return;
  13881. this._gl.uniform1iv(uniform, array);
  13882. };
  13883. /**
  13884. * Set the value of an uniform to an array of int32 (stored as vec2)
  13885. * @param uniform defines the webGL uniform location where to store the value
  13886. * @param array defines the array of int32 to store
  13887. */
  13888. Engine.prototype.setIntArray2 = function (uniform, array) {
  13889. if (!uniform || array.length % 2 !== 0)
  13890. return;
  13891. this._gl.uniform2iv(uniform, array);
  13892. };
  13893. /**
  13894. * Set the value of an uniform to an array of int32 (stored as vec3)
  13895. * @param uniform defines the webGL uniform location where to store the value
  13896. * @param array defines the array of int32 to store
  13897. */
  13898. Engine.prototype.setIntArray3 = function (uniform, array) {
  13899. if (!uniform || array.length % 3 !== 0)
  13900. return;
  13901. this._gl.uniform3iv(uniform, array);
  13902. };
  13903. /**
  13904. * Set the value of an uniform to an array of int32 (stored as vec4)
  13905. * @param uniform defines the webGL uniform location where to store the value
  13906. * @param array defines the array of int32 to store
  13907. */
  13908. Engine.prototype.setIntArray4 = function (uniform, array) {
  13909. if (!uniform || array.length % 4 !== 0)
  13910. return;
  13911. this._gl.uniform4iv(uniform, array);
  13912. };
  13913. /**
  13914. * Set the value of an uniform to an array of float32
  13915. * @param uniform defines the webGL uniform location where to store the value
  13916. * @param array defines the array of float32 to store
  13917. */
  13918. Engine.prototype.setFloatArray = function (uniform, array) {
  13919. if (!uniform)
  13920. return;
  13921. this._gl.uniform1fv(uniform, array);
  13922. };
  13923. /**
  13924. * Set the value of an uniform to an array of float32 (stored as vec2)
  13925. * @param uniform defines the webGL uniform location where to store the value
  13926. * @param array defines the array of float32 to store
  13927. */
  13928. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13929. if (!uniform || array.length % 2 !== 0)
  13930. return;
  13931. this._gl.uniform2fv(uniform, array);
  13932. };
  13933. /**
  13934. * Set the value of an uniform to an array of float32 (stored as vec3)
  13935. * @param uniform defines the webGL uniform location where to store the value
  13936. * @param array defines the array of float32 to store
  13937. */
  13938. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13939. if (!uniform || array.length % 3 !== 0)
  13940. return;
  13941. this._gl.uniform3fv(uniform, array);
  13942. };
  13943. /**
  13944. * Set the value of an uniform to an array of float32 (stored as vec4)
  13945. * @param uniform defines the webGL uniform location where to store the value
  13946. * @param array defines the array of float32 to store
  13947. */
  13948. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13949. if (!uniform || array.length % 4 !== 0)
  13950. return;
  13951. this._gl.uniform4fv(uniform, array);
  13952. };
  13953. /**
  13954. * Set the value of an uniform to an array of number
  13955. * @param uniform defines the webGL uniform location where to store the value
  13956. * @param array defines the array of number to store
  13957. */
  13958. Engine.prototype.setArray = function (uniform, array) {
  13959. if (!uniform)
  13960. return;
  13961. this._gl.uniform1fv(uniform, array);
  13962. };
  13963. /**
  13964. * Set the value of an uniform to an array of number (stored as vec2)
  13965. * @param uniform defines the webGL uniform location where to store the value
  13966. * @param array defines the array of number to store
  13967. */
  13968. Engine.prototype.setArray2 = function (uniform, array) {
  13969. if (!uniform || array.length % 2 !== 0)
  13970. return;
  13971. this._gl.uniform2fv(uniform, array);
  13972. };
  13973. /**
  13974. * Set the value of an uniform to an array of number (stored as vec3)
  13975. * @param uniform defines the webGL uniform location where to store the value
  13976. * @param array defines the array of number to store
  13977. */
  13978. Engine.prototype.setArray3 = function (uniform, array) {
  13979. if (!uniform || array.length % 3 !== 0)
  13980. return;
  13981. this._gl.uniform3fv(uniform, array);
  13982. };
  13983. /**
  13984. * Set the value of an uniform to an array of number (stored as vec4)
  13985. * @param uniform defines the webGL uniform location where to store the value
  13986. * @param array defines the array of number to store
  13987. */
  13988. Engine.prototype.setArray4 = function (uniform, array) {
  13989. if (!uniform || array.length % 4 !== 0)
  13990. return;
  13991. this._gl.uniform4fv(uniform, array);
  13992. };
  13993. /**
  13994. * Set the value of an uniform to an array of float32 (stored as matrices)
  13995. * @param uniform defines the webGL uniform location where to store the value
  13996. * @param matrices defines the array of float32 to store
  13997. */
  13998. Engine.prototype.setMatrices = function (uniform, matrices) {
  13999. if (!uniform)
  14000. return;
  14001. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14002. };
  14003. /**
  14004. * Set the value of an uniform to a matrix
  14005. * @param uniform defines the webGL uniform location where to store the value
  14006. * @param matrix defines the matrix to store
  14007. */
  14008. Engine.prototype.setMatrix = function (uniform, matrix) {
  14009. if (!uniform)
  14010. return;
  14011. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14012. };
  14013. /**
  14014. * Set the value of an uniform to a matrix (3x3)
  14015. * @param uniform defines the webGL uniform location where to store the value
  14016. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14017. */
  14018. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14019. if (!uniform)
  14020. return;
  14021. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14022. };
  14023. /**
  14024. * Set the value of an uniform to a matrix (2x2)
  14025. * @param uniform defines the webGL uniform location where to store the value
  14026. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14027. */
  14028. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14029. if (!uniform)
  14030. return;
  14031. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14032. };
  14033. /**
  14034. * Set the value of an uniform to a number (int)
  14035. * @param uniform defines the webGL uniform location where to store the value
  14036. * @param value defines the int number to store
  14037. */
  14038. Engine.prototype.setInt = function (uniform, value) {
  14039. if (!uniform)
  14040. return;
  14041. this._gl.uniform1i(uniform, value);
  14042. };
  14043. /**
  14044. * Set the value of an uniform to a number (float)
  14045. * @param uniform defines the webGL uniform location where to store the value
  14046. * @param value defines the float number to store
  14047. */
  14048. Engine.prototype.setFloat = function (uniform, value) {
  14049. if (!uniform)
  14050. return;
  14051. this._gl.uniform1f(uniform, value);
  14052. };
  14053. /**
  14054. * Set the value of an uniform to a vec2
  14055. * @param uniform defines the webGL uniform location where to store the value
  14056. * @param x defines the 1st component of the value
  14057. * @param y defines the 2nd component of the value
  14058. */
  14059. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14060. if (!uniform)
  14061. return;
  14062. this._gl.uniform2f(uniform, x, y);
  14063. };
  14064. /**
  14065. * Set the value of an uniform to a vec3
  14066. * @param uniform defines the webGL uniform location where to store the value
  14067. * @param x defines the 1st component of the value
  14068. * @param y defines the 2nd component of the value
  14069. * @param z defines the 3rd component of the value
  14070. */
  14071. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14072. if (!uniform)
  14073. return;
  14074. this._gl.uniform3f(uniform, x, y, z);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to a boolean
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param bool defines the boolean to store
  14080. */
  14081. Engine.prototype.setBool = function (uniform, bool) {
  14082. if (!uniform)
  14083. return;
  14084. this._gl.uniform1i(uniform, bool);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to a vec4
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param x defines the 1st component of the value
  14090. * @param y defines the 2nd component of the value
  14091. * @param z defines the 3rd component of the value
  14092. * @param w defines the 4th component of the value
  14093. */
  14094. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14095. if (!uniform)
  14096. return;
  14097. this._gl.uniform4f(uniform, x, y, z, w);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to a Color3
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param color3 defines the color to store
  14103. */
  14104. Engine.prototype.setColor3 = function (uniform, color3) {
  14105. if (!uniform)
  14106. return;
  14107. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to a Color3 and an alpha value
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param color3 defines the color to store
  14113. * @param alpha defines the alpha component to store
  14114. */
  14115. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14116. if (!uniform)
  14117. return;
  14118. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14119. };
  14120. /**
  14121. * Sets a Color4 on a uniform variable
  14122. * @param uniform defines the uniform location
  14123. * @param color4 defines the value to be set
  14124. */
  14125. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14126. if (!uniform)
  14127. return;
  14128. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14129. };
  14130. // States
  14131. /**
  14132. * Set various states to the webGL context
  14133. * @param culling defines backface culling state
  14134. * @param zOffset defines the value to apply to zOffset (0 by default)
  14135. * @param force defines if states must be applied even if cache is up to date
  14136. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14137. */
  14138. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14139. if (zOffset === void 0) { zOffset = 0; }
  14140. if (reverseSide === void 0) { reverseSide = false; }
  14141. // Culling
  14142. if (this._depthCullingState.cull !== culling || force) {
  14143. this._depthCullingState.cull = culling;
  14144. }
  14145. // Cull face
  14146. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14147. if (this._depthCullingState.cullFace !== cullFace || force) {
  14148. this._depthCullingState.cullFace = cullFace;
  14149. }
  14150. // Z offset
  14151. this.setZOffset(zOffset);
  14152. // Front face
  14153. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14154. if (this._depthCullingState.frontFace !== frontFace || force) {
  14155. this._depthCullingState.frontFace = frontFace;
  14156. }
  14157. };
  14158. /**
  14159. * Set the z offset to apply to current rendering
  14160. * @param value defines the offset to apply
  14161. */
  14162. Engine.prototype.setZOffset = function (value) {
  14163. this._depthCullingState.zOffset = value;
  14164. };
  14165. /**
  14166. * Gets the current value of the zOffset
  14167. * @returns the current zOffset state
  14168. */
  14169. Engine.prototype.getZOffset = function () {
  14170. return this._depthCullingState.zOffset;
  14171. };
  14172. /**
  14173. * Enable or disable depth buffering
  14174. * @param enable defines the state to set
  14175. */
  14176. Engine.prototype.setDepthBuffer = function (enable) {
  14177. this._depthCullingState.depthTest = enable;
  14178. };
  14179. /**
  14180. * Gets a boolean indicating if depth writing is enabled
  14181. * @returns the current depth writing state
  14182. */
  14183. Engine.prototype.getDepthWrite = function () {
  14184. return this._depthCullingState.depthMask;
  14185. };
  14186. /**
  14187. * Enable or disable depth writing
  14188. * @param enable defines the state to set
  14189. */
  14190. Engine.prototype.setDepthWrite = function (enable) {
  14191. this._depthCullingState.depthMask = enable;
  14192. };
  14193. /**
  14194. * Enable or disable color writing
  14195. * @param enable defines the state to set
  14196. */
  14197. Engine.prototype.setColorWrite = function (enable) {
  14198. this._gl.colorMask(enable, enable, enable, enable);
  14199. this._colorWrite = enable;
  14200. };
  14201. /**
  14202. * Gets a boolean indicating if color writing is enabled
  14203. * @returns the current color writing state
  14204. */
  14205. Engine.prototype.getColorWrite = function () {
  14206. return this._colorWrite;
  14207. };
  14208. /**
  14209. * Sets alpha constants used by some alpha blending modes
  14210. * @param r defines the red component
  14211. * @param g defines the green component
  14212. * @param b defines the blue component
  14213. * @param a defines the alpha component
  14214. */
  14215. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14216. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14217. };
  14218. /**
  14219. * Sets the current alpha mode
  14220. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14221. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14222. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14223. */
  14224. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14225. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14226. if (this._alphaMode === mode) {
  14227. return;
  14228. }
  14229. switch (mode) {
  14230. case Engine.ALPHA_DISABLE:
  14231. this._alphaState.alphaBlend = false;
  14232. break;
  14233. case Engine.ALPHA_PREMULTIPLIED:
  14234. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14235. this._alphaState.alphaBlend = true;
  14236. break;
  14237. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14239. this._alphaState.alphaBlend = true;
  14240. break;
  14241. case Engine.ALPHA_COMBINE:
  14242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14243. this._alphaState.alphaBlend = true;
  14244. break;
  14245. case Engine.ALPHA_ONEONE:
  14246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14247. this._alphaState.alphaBlend = true;
  14248. break;
  14249. case Engine.ALPHA_ADD:
  14250. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14251. this._alphaState.alphaBlend = true;
  14252. break;
  14253. case Engine.ALPHA_SUBTRACT:
  14254. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14255. this._alphaState.alphaBlend = true;
  14256. break;
  14257. case Engine.ALPHA_MULTIPLY:
  14258. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14259. this._alphaState.alphaBlend = true;
  14260. break;
  14261. case Engine.ALPHA_MAXIMIZED:
  14262. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14263. this._alphaState.alphaBlend = true;
  14264. break;
  14265. case Engine.ALPHA_INTERPOLATE:
  14266. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14267. this._alphaState.alphaBlend = true;
  14268. break;
  14269. case Engine.ALPHA_SCREENMODE:
  14270. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14271. this._alphaState.alphaBlend = true;
  14272. break;
  14273. }
  14274. if (!noDepthWriteChange) {
  14275. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14276. }
  14277. this._alphaMode = mode;
  14278. };
  14279. /**
  14280. * Gets the current alpha mode
  14281. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14282. * @returns the current alpha mode
  14283. */
  14284. Engine.prototype.getAlphaMode = function () {
  14285. return this._alphaMode;
  14286. };
  14287. // Textures
  14288. /**
  14289. * Force the entire cache to be cleared
  14290. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14291. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14292. */
  14293. Engine.prototype.wipeCaches = function (bruteForce) {
  14294. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14295. return;
  14296. }
  14297. this._currentEffect = null;
  14298. if (bruteForce) {
  14299. this.resetTextureCache();
  14300. this._currentProgram = null;
  14301. this._stencilState.reset();
  14302. this._depthCullingState.reset();
  14303. this.setDepthFunctionToLessOrEqual();
  14304. this._alphaState.reset();
  14305. }
  14306. this._resetVertexBufferBinding();
  14307. this._cachedIndexBuffer = null;
  14308. this._cachedEffectForVertexBuffers = null;
  14309. this._unbindVertexArrayObject();
  14310. this.bindIndexBuffer(null);
  14311. };
  14312. /**
  14313. * Set the compressed texture format to use, based on the formats you have, and the formats
  14314. * supported by the hardware / browser.
  14315. *
  14316. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14317. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14318. * to API arguments needed to compressed textures. This puts the burden on the container
  14319. * generator to house the arcane code for determining these for current & future formats.
  14320. *
  14321. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14322. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14323. *
  14324. * Note: The result of this call is not taken into account when a texture is base64.
  14325. *
  14326. * @param formatsAvailable defines the list of those format families you have created
  14327. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14328. *
  14329. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14330. * @returns The extension selected.
  14331. */
  14332. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14333. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14334. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14335. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14336. return this._textureFormatInUse = this._texturesSupported[i];
  14337. }
  14338. }
  14339. }
  14340. // actively set format to nothing, to allow this to be called more than once
  14341. // and possibly fail the 2nd time
  14342. this._textureFormatInUse = null;
  14343. return null;
  14344. };
  14345. /** @ignore */
  14346. Engine.prototype._createTexture = function () {
  14347. var texture = this._gl.createTexture();
  14348. if (!texture) {
  14349. throw new Error("Unable to create texture");
  14350. }
  14351. return texture;
  14352. };
  14353. /**
  14354. * Usually called from BABYLON.Texture.ts.
  14355. * Passed information to create a WebGLTexture
  14356. * @param urlArg defines a value which contains one of the following:
  14357. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14358. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14359. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14360. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14361. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14362. * @param scene needed for loading to the correct scene
  14363. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14364. * @param onLoad optional callback to be called upon successful completion
  14365. * @param onError optional callback to be called upon failure
  14366. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14367. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14368. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14369. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14370. */
  14371. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14372. var _this = this;
  14373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14374. if (onLoad === void 0) { onLoad = null; }
  14375. if (onError === void 0) { onError = null; }
  14376. if (buffer === void 0) { buffer = null; }
  14377. if (fallback === void 0) { fallback = null; }
  14378. if (format === void 0) { format = null; }
  14379. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14380. var fromData = url.substr(0, 5) === "data:";
  14381. var fromBlob = url.substr(0, 5) === "blob:";
  14382. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14383. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14384. // establish the file extension, if possible
  14385. var lastDot = url.lastIndexOf('.');
  14386. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14387. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14388. var isTGA = (extension.indexOf(".tga") === 0);
  14389. // determine if a ktx file should be substituted
  14390. var isKTX = false;
  14391. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14392. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14393. isKTX = true;
  14394. }
  14395. if (scene) {
  14396. scene._addPendingData(texture);
  14397. }
  14398. texture.url = url;
  14399. texture.generateMipMaps = !noMipmap;
  14400. texture.samplingMode = samplingMode;
  14401. texture.invertY = invertY;
  14402. if (!this._doNotHandleContextLost) {
  14403. // Keep a link to the buffer only if we plan to handle context lost
  14404. texture._buffer = buffer;
  14405. }
  14406. var onLoadObserver = null;
  14407. if (onLoad && !fallback) {
  14408. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14409. }
  14410. if (!fallback)
  14411. this._internalTexturesCache.push(texture);
  14412. var onerror = function (message, exception) {
  14413. if (scene) {
  14414. scene._removePendingData(texture);
  14415. }
  14416. if (onLoadObserver) {
  14417. texture.onLoadedObservable.remove(onLoadObserver);
  14418. }
  14419. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14420. if (isKTX) {
  14421. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14422. }
  14423. else if (BABYLON.Tools.UseFallbackTexture) {
  14424. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14425. }
  14426. if (onError) {
  14427. onError(message || "Unknown error", exception);
  14428. }
  14429. };
  14430. var callback = null;
  14431. // processing for non-image formats
  14432. if (isKTX || isTGA || isDDS) {
  14433. if (isKTX) {
  14434. callback = function (data) {
  14435. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14436. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14437. ktx.uploadLevels(_this._gl, !noMipmap);
  14438. return false;
  14439. }, samplingMode);
  14440. };
  14441. }
  14442. else if (isTGA) {
  14443. callback = function (arrayBuffer) {
  14444. var data = new Uint8Array(arrayBuffer);
  14445. var header = BABYLON.TGATools.GetTGAHeader(data);
  14446. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14447. BABYLON.TGATools.UploadContent(_this._gl, data);
  14448. return false;
  14449. }, samplingMode);
  14450. };
  14451. }
  14452. else if (isDDS) {
  14453. callback = function (data) {
  14454. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14455. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14456. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14457. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14458. return false;
  14459. }, samplingMode);
  14460. };
  14461. }
  14462. if (!buffer) {
  14463. this._loadFile(url, function (data) {
  14464. if (callback) {
  14465. callback(data);
  14466. }
  14467. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14468. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14469. });
  14470. }
  14471. else {
  14472. if (callback) {
  14473. callback(buffer);
  14474. }
  14475. }
  14476. // image format processing
  14477. }
  14478. else {
  14479. var onload = function (img) {
  14480. if (fromBlob && !_this._doNotHandleContextLost) {
  14481. // We need to store the image if we need to rebuild the texture
  14482. // in case of a webgl context lost
  14483. texture._buffer = img;
  14484. }
  14485. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14486. var gl = _this._gl;
  14487. var isPot = (img.width === potWidth && img.height === potHeight);
  14488. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14489. if (isPot) {
  14490. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14491. return false;
  14492. }
  14493. // Using shaders to rescale because canvas.drawImage is lossy
  14494. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14495. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14496. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14497. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14501. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14502. _this._releaseTexture(source);
  14503. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14504. continuationCallback();
  14505. });
  14506. return true;
  14507. }, samplingMode);
  14508. };
  14509. if (!fromData || isBase64)
  14510. if (buffer instanceof HTMLImageElement) {
  14511. onload(buffer);
  14512. }
  14513. else {
  14514. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14515. }
  14516. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14517. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14518. else
  14519. onload(buffer);
  14520. }
  14521. return texture;
  14522. };
  14523. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14524. var _this = this;
  14525. var rtt = this.createRenderTargetTexture({
  14526. width: destination.width,
  14527. height: destination.height,
  14528. }, {
  14529. generateMipMaps: false,
  14530. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14531. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14532. generateDepthBuffer: false,
  14533. generateStencilBuffer: false
  14534. });
  14535. if (!this._rescalePostProcess) {
  14536. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14537. }
  14538. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14539. _this._rescalePostProcess.onApply = function (effect) {
  14540. effect._bindTexture("textureSampler", source);
  14541. };
  14542. var hostingScene = scene;
  14543. if (!hostingScene) {
  14544. hostingScene = _this.scenes[_this.scenes.length - 1];
  14545. }
  14546. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14547. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14548. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14549. _this.unBindFramebuffer(rtt);
  14550. _this._releaseTexture(rtt);
  14551. if (onComplete) {
  14552. onComplete();
  14553. }
  14554. });
  14555. };
  14556. /**
  14557. * Update a raw texture
  14558. * @param texture defines the texture to update
  14559. * @param data defines the data to store in the texture
  14560. * @param format defines the format of the data
  14561. * @param invertY defines if data must be stored with Y axis inverted
  14562. * @param compression defines the compression used (null by default)
  14563. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14564. */
  14565. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14566. if (compression === void 0) { compression = null; }
  14567. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14568. if (!texture) {
  14569. return;
  14570. }
  14571. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14572. var internalFormat = this._getInternalFormat(format);
  14573. var textureType = this._getWebGLTextureType(type);
  14574. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14575. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14576. if (!this._doNotHandleContextLost) {
  14577. texture._bufferView = data;
  14578. texture.format = format;
  14579. texture.type = type;
  14580. texture.invertY = invertY;
  14581. texture._compression = compression;
  14582. }
  14583. if (texture.width % 4 !== 0) {
  14584. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14585. }
  14586. if (compression && data) {
  14587. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14588. }
  14589. else {
  14590. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14591. }
  14592. if (texture.generateMipMaps) {
  14593. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14594. }
  14595. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14596. // this.resetTextureCache();
  14597. texture.isReady = true;
  14598. };
  14599. /**
  14600. * Creates a raw texture
  14601. * @param data defines the data to store in the texture
  14602. * @param width defines the width of the texture
  14603. * @param height defines the height of the texture
  14604. * @param format defines the format of the data
  14605. * @param generateMipMaps defines if the engine should generate the mip levels
  14606. * @param invertY defines if data must be stored with Y axis inverted
  14607. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14608. * @param compression defines the compression used (null by default)
  14609. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14610. * @returns the raw texture inside an InternalTexture
  14611. */
  14612. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14613. if (compression === void 0) { compression = null; }
  14614. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14615. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14616. texture.baseWidth = width;
  14617. texture.baseHeight = height;
  14618. texture.width = width;
  14619. texture.height = height;
  14620. texture.format = format;
  14621. texture.generateMipMaps = generateMipMaps;
  14622. texture.samplingMode = samplingMode;
  14623. texture.invertY = invertY;
  14624. texture._compression = compression;
  14625. texture.type = type;
  14626. if (!this._doNotHandleContextLost) {
  14627. texture._bufferView = data;
  14628. }
  14629. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14630. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14631. // Filters
  14632. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14633. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14634. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14635. if (generateMipMaps) {
  14636. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14637. }
  14638. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14639. this._internalTexturesCache.push(texture);
  14640. return texture;
  14641. };
  14642. /**
  14643. * Creates a dynamic texture
  14644. * @param width defines the width of the texture
  14645. * @param height defines the height of the texture
  14646. * @param generateMipMaps defines if the engine should generate the mip levels
  14647. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14648. * @returns the dynamic texture inside an InternalTexture
  14649. */
  14650. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14651. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14652. texture.baseWidth = width;
  14653. texture.baseHeight = height;
  14654. if (generateMipMaps) {
  14655. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14656. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14657. }
  14658. // this.resetTextureCache();
  14659. texture.width = width;
  14660. texture.height = height;
  14661. texture.isReady = false;
  14662. texture.generateMipMaps = generateMipMaps;
  14663. texture.samplingMode = samplingMode;
  14664. this.updateTextureSamplingMode(samplingMode, texture);
  14665. this._internalTexturesCache.push(texture);
  14666. return texture;
  14667. };
  14668. /**
  14669. * Update the sampling mode of a given texture
  14670. * @param samplingMode defines the required sampling mode
  14671. * @param texture defines the texture to update
  14672. */
  14673. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14674. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14675. if (texture.isCube) {
  14676. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14677. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14678. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14679. }
  14680. else if (texture.is3D) {
  14681. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14682. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14683. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14684. }
  14685. else {
  14686. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14687. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14688. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14689. }
  14690. texture.samplingMode = samplingMode;
  14691. };
  14692. /**
  14693. * Update the content of a dynamic texture
  14694. * @param texture defines the texture to update
  14695. * @param canvas defines the canvas containing the source
  14696. * @param invertY defines if data must be stored with Y axis inverted
  14697. * @param premulAlpha defines if alpha is stored as premultiplied
  14698. * @param format defines the format of the data
  14699. */
  14700. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14701. if (premulAlpha === void 0) { premulAlpha = false; }
  14702. if (!texture) {
  14703. return;
  14704. }
  14705. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14706. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14707. if (premulAlpha) {
  14708. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14709. }
  14710. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14711. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14712. if (texture.generateMipMaps) {
  14713. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14714. }
  14715. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14716. if (premulAlpha) {
  14717. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14718. }
  14719. texture.isReady = true;
  14720. };
  14721. /**
  14722. * Update a video texture
  14723. * @param texture defines the texture to update
  14724. * @param video defines the video element to use
  14725. * @param invertY defines if data must be stored with Y axis inverted
  14726. */
  14727. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14728. if (!texture || texture._isDisabled) {
  14729. return;
  14730. }
  14731. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14732. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14733. try {
  14734. // Testing video texture support
  14735. if (this._videoTextureSupported === undefined) {
  14736. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14737. if (this._gl.getError() !== 0) {
  14738. this._videoTextureSupported = false;
  14739. }
  14740. else {
  14741. this._videoTextureSupported = true;
  14742. }
  14743. }
  14744. // Copy video through the current working canvas if video texture is not supported
  14745. if (!this._videoTextureSupported) {
  14746. if (!texture._workingCanvas) {
  14747. texture._workingCanvas = document.createElement("canvas");
  14748. var context = texture._workingCanvas.getContext("2d");
  14749. if (!context) {
  14750. throw new Error("Unable to get 2d context");
  14751. }
  14752. texture._workingContext = context;
  14753. texture._workingCanvas.width = texture.width;
  14754. texture._workingCanvas.height = texture.height;
  14755. }
  14756. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14757. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14758. }
  14759. else {
  14760. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14761. }
  14762. if (texture.generateMipMaps) {
  14763. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14764. }
  14765. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14766. // this.resetTextureCache();
  14767. texture.isReady = true;
  14768. }
  14769. catch (ex) {
  14770. // Something unexpected
  14771. // Let's disable the texture
  14772. texture._isDisabled = true;
  14773. }
  14774. };
  14775. /**
  14776. * Updates a depth texture Comparison Mode and Function.
  14777. * If the comparison Function is equal to 0, the mode will be set to none.
  14778. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14779. * @param texture The texture to set the comparison function for
  14780. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14781. */
  14782. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14783. if (this.webGLVersion === 1) {
  14784. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14785. return;
  14786. }
  14787. var gl = this._gl;
  14788. if (texture.isCube) {
  14789. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14790. if (comparisonFunction === 0) {
  14791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14793. }
  14794. else {
  14795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14797. }
  14798. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14799. }
  14800. else {
  14801. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14802. if (comparisonFunction === 0) {
  14803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14805. }
  14806. else {
  14807. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14808. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14809. }
  14810. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14811. }
  14812. texture._comparisonFunction = comparisonFunction;
  14813. };
  14814. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14815. var width = size.width || size;
  14816. var height = size.height || size;
  14817. internalTexture.baseWidth = width;
  14818. internalTexture.baseHeight = height;
  14819. internalTexture.width = width;
  14820. internalTexture.height = height;
  14821. internalTexture.isReady = true;
  14822. internalTexture.samples = 1;
  14823. internalTexture.generateMipMaps = false;
  14824. internalTexture._generateDepthBuffer = true;
  14825. internalTexture._generateStencilBuffer = generateStencil;
  14826. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14827. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14828. internalTexture._comparisonFunction = comparisonFunction;
  14829. var gl = this._gl;
  14830. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14831. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14832. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14833. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14834. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14835. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14836. if (comparisonFunction === 0) {
  14837. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14838. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14839. }
  14840. else {
  14841. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14842. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14843. }
  14844. };
  14845. /**
  14846. * Creates a depth stencil texture.
  14847. * This is only available in WebGL 2 or with the depth texture extension available.
  14848. * @param size The size of face edge in the texture.
  14849. * @param options The options defining the texture.
  14850. * @returns The texture
  14851. */
  14852. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14853. if (options.isCube) {
  14854. var width = size.width || size;
  14855. return this._createDepthStencilCubeTexture(width, options);
  14856. }
  14857. else {
  14858. return this._createDepthStencilTexture(size, options);
  14859. }
  14860. };
  14861. /**
  14862. * Creates a depth stencil texture.
  14863. * This is only available in WebGL 2 or with the depth texture extension available.
  14864. * @param size The size of face edge in the texture.
  14865. * @param options The options defining the texture.
  14866. * @returns The texture
  14867. */
  14868. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14869. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14870. if (!this._caps.depthTextureExtension) {
  14871. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14872. return internalTexture;
  14873. }
  14874. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14875. var gl = this._gl;
  14876. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14877. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14878. if (this.webGLVersion > 1) {
  14879. if (internalOptions.generateStencil) {
  14880. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14881. }
  14882. else {
  14883. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14884. }
  14885. }
  14886. else {
  14887. if (internalOptions.generateStencil) {
  14888. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14889. }
  14890. else {
  14891. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14892. }
  14893. }
  14894. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14895. return internalTexture;
  14896. };
  14897. /**
  14898. * Creates a depth stencil cube texture.
  14899. * This is only available in WebGL 2.
  14900. * @param size The size of face edge in the cube texture.
  14901. * @param options The options defining the cube texture.
  14902. * @returns The cube texture
  14903. */
  14904. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14905. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14906. internalTexture.isCube = true;
  14907. if (this.webGLVersion === 1) {
  14908. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14909. return internalTexture;
  14910. }
  14911. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14912. var gl = this._gl;
  14913. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14914. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14915. // Create the depth/stencil buffer
  14916. for (var face = 0; face < 6; face++) {
  14917. if (internalOptions.generateStencil) {
  14918. 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);
  14919. }
  14920. else {
  14921. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14922. }
  14923. }
  14924. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14925. return internalTexture;
  14926. };
  14927. /**
  14928. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14929. * @param renderTarget The render target to set the frame buffer for
  14930. */
  14931. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14932. // Create the framebuffer
  14933. var internalTexture = renderTarget.getInternalTexture();
  14934. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14935. return;
  14936. }
  14937. var gl = this._gl;
  14938. var depthStencilTexture = renderTarget.depthStencilTexture;
  14939. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14940. if (depthStencilTexture.isCube) {
  14941. if (depthStencilTexture._generateStencilBuffer) {
  14942. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14943. }
  14944. else {
  14945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14946. }
  14947. }
  14948. else {
  14949. if (depthStencilTexture._generateStencilBuffer) {
  14950. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14951. }
  14952. else {
  14953. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14954. }
  14955. }
  14956. this.bindUnboundFramebuffer(null);
  14957. };
  14958. /**
  14959. * Creates a new render target texture
  14960. * @param size defines the size of the texture
  14961. * @param options defines the options used to create the texture
  14962. * @returns a new render target texture stored in an InternalTexture
  14963. */
  14964. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14965. var fullOptions = new RenderTargetCreationOptions();
  14966. if (options !== undefined && typeof options === "object") {
  14967. fullOptions.generateMipMaps = options.generateMipMaps;
  14968. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14969. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14970. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14971. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14972. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14973. }
  14974. else {
  14975. fullOptions.generateMipMaps = options;
  14976. fullOptions.generateDepthBuffer = true;
  14977. fullOptions.generateStencilBuffer = false;
  14978. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14979. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14980. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14981. }
  14982. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14983. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14984. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14985. }
  14986. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14987. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14988. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14989. }
  14990. var gl = this._gl;
  14991. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14992. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14993. var width = size.width || size;
  14994. var height = size.height || size;
  14995. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14996. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14997. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14998. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14999. }
  15000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15003. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15004. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15005. // Create the framebuffer
  15006. var framebuffer = gl.createFramebuffer();
  15007. this.bindUnboundFramebuffer(framebuffer);
  15008. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15009. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15010. if (fullOptions.generateMipMaps) {
  15011. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15012. }
  15013. // Unbind
  15014. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15015. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15016. this.bindUnboundFramebuffer(null);
  15017. texture._framebuffer = framebuffer;
  15018. texture.baseWidth = width;
  15019. texture.baseHeight = height;
  15020. texture.width = width;
  15021. texture.height = height;
  15022. texture.isReady = true;
  15023. texture.samples = 1;
  15024. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15025. texture.samplingMode = fullOptions.samplingMode;
  15026. texture.type = fullOptions.type;
  15027. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15028. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15029. // this.resetTextureCache();
  15030. this._internalTexturesCache.push(texture);
  15031. return texture;
  15032. };
  15033. /**
  15034. * Create a multi render target texture
  15035. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15036. * @param size defines the size of the texture
  15037. * @param options defines the creation options
  15038. * @returns the cube texture as an InternalTexture
  15039. */
  15040. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15041. var generateMipMaps = false;
  15042. var generateDepthBuffer = true;
  15043. var generateStencilBuffer = false;
  15044. var generateDepthTexture = false;
  15045. var textureCount = 1;
  15046. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15047. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15048. var types = new Array();
  15049. var samplingModes = new Array();
  15050. if (options !== undefined) {
  15051. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15052. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15053. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15054. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15055. textureCount = options.textureCount || 1;
  15056. if (options.types) {
  15057. types = options.types;
  15058. }
  15059. if (options.samplingModes) {
  15060. samplingModes = options.samplingModes;
  15061. }
  15062. }
  15063. var gl = this._gl;
  15064. // Create the framebuffer
  15065. var framebuffer = gl.createFramebuffer();
  15066. this.bindUnboundFramebuffer(framebuffer);
  15067. var width = size.width || size;
  15068. var height = size.height || size;
  15069. var textures = [];
  15070. var attachments = [];
  15071. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15072. for (var i = 0; i < textureCount; i++) {
  15073. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15074. var type = types[i] || defaultType;
  15075. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15076. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15077. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15078. }
  15079. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15080. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15081. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15082. }
  15083. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15084. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15085. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15086. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15087. }
  15088. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15089. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15090. textures.push(texture);
  15091. attachments.push(attachment);
  15092. gl.activeTexture(gl["TEXTURE" + i]);
  15093. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15095. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15096. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15098. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15099. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15100. if (generateMipMaps) {
  15101. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15102. }
  15103. // Unbind
  15104. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15105. texture._framebuffer = framebuffer;
  15106. texture._depthStencilBuffer = depthStencilBuffer;
  15107. texture.baseWidth = width;
  15108. texture.baseHeight = height;
  15109. texture.width = width;
  15110. texture.height = height;
  15111. texture.isReady = true;
  15112. texture.samples = 1;
  15113. texture.generateMipMaps = generateMipMaps;
  15114. texture.samplingMode = samplingMode;
  15115. texture.type = type;
  15116. texture._generateDepthBuffer = generateDepthBuffer;
  15117. texture._generateStencilBuffer = generateStencilBuffer;
  15118. texture._attachments = attachments;
  15119. this._internalTexturesCache.push(texture);
  15120. }
  15121. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15122. // Depth texture
  15123. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15124. gl.activeTexture(gl.TEXTURE0);
  15125. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15129. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15130. 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);
  15131. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15132. depthTexture._framebuffer = framebuffer;
  15133. depthTexture.baseWidth = width;
  15134. depthTexture.baseHeight = height;
  15135. depthTexture.width = width;
  15136. depthTexture.height = height;
  15137. depthTexture.isReady = true;
  15138. depthTexture.samples = 1;
  15139. depthTexture.generateMipMaps = generateMipMaps;
  15140. depthTexture.samplingMode = gl.NEAREST;
  15141. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15142. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15143. textures.push(depthTexture);
  15144. this._internalTexturesCache.push(depthTexture);
  15145. }
  15146. gl.drawBuffers(attachments);
  15147. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15148. this.bindUnboundFramebuffer(null);
  15149. this.resetTextureCache();
  15150. return textures;
  15151. };
  15152. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15153. if (samples === void 0) { samples = 1; }
  15154. var depthStencilBuffer = null;
  15155. var gl = this._gl;
  15156. // Create the depth/stencil buffer
  15157. if (generateStencilBuffer) {
  15158. depthStencilBuffer = gl.createRenderbuffer();
  15159. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15160. if (samples > 1) {
  15161. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15162. }
  15163. else {
  15164. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15165. }
  15166. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15167. }
  15168. else if (generateDepthBuffer) {
  15169. depthStencilBuffer = gl.createRenderbuffer();
  15170. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15171. if (samples > 1) {
  15172. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15173. }
  15174. else {
  15175. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15176. }
  15177. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15178. }
  15179. return depthStencilBuffer;
  15180. };
  15181. /**
  15182. * Updates the sample count of a render target texture
  15183. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15184. * @param texture defines the texture to update
  15185. * @param samples defines the sample count to set
  15186. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15187. */
  15188. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15189. if (this.webGLVersion < 2 || !texture) {
  15190. return 1;
  15191. }
  15192. if (texture.samples === samples) {
  15193. return samples;
  15194. }
  15195. var gl = this._gl;
  15196. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15197. // Dispose previous render buffers
  15198. if (texture._depthStencilBuffer) {
  15199. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15200. texture._depthStencilBuffer = null;
  15201. }
  15202. if (texture._MSAAFramebuffer) {
  15203. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15204. texture._MSAAFramebuffer = null;
  15205. }
  15206. if (texture._MSAARenderBuffer) {
  15207. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15208. texture._MSAARenderBuffer = null;
  15209. }
  15210. if (samples > 1) {
  15211. var framebuffer = gl.createFramebuffer();
  15212. if (!framebuffer) {
  15213. throw new Error("Unable to create multi sampled framebuffer");
  15214. }
  15215. texture._MSAAFramebuffer = framebuffer;
  15216. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15217. var colorRenderbuffer = gl.createRenderbuffer();
  15218. if (!colorRenderbuffer) {
  15219. throw new Error("Unable to create multi sampled framebuffer");
  15220. }
  15221. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15222. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15223. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15224. texture._MSAARenderBuffer = colorRenderbuffer;
  15225. }
  15226. else {
  15227. this.bindUnboundFramebuffer(texture._framebuffer);
  15228. }
  15229. texture.samples = samples;
  15230. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15231. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15232. this.bindUnboundFramebuffer(null);
  15233. return samples;
  15234. };
  15235. /**
  15236. * Update the sample count for a given multiple render target texture
  15237. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15238. * @param textures defines the textures to update
  15239. * @param samples defines the sample count to set
  15240. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15241. */
  15242. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15243. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15244. return 1;
  15245. }
  15246. if (textures[0].samples === samples) {
  15247. return samples;
  15248. }
  15249. var gl = this._gl;
  15250. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15251. // Dispose previous render buffers
  15252. if (textures[0]._depthStencilBuffer) {
  15253. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15254. textures[0]._depthStencilBuffer = null;
  15255. }
  15256. if (textures[0]._MSAAFramebuffer) {
  15257. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15258. textures[0]._MSAAFramebuffer = null;
  15259. }
  15260. for (var i = 0; i < textures.length; i++) {
  15261. if (textures[i]._MSAARenderBuffer) {
  15262. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15263. textures[i]._MSAARenderBuffer = null;
  15264. }
  15265. }
  15266. if (samples > 1) {
  15267. var framebuffer = gl.createFramebuffer();
  15268. if (!framebuffer) {
  15269. throw new Error("Unable to create multi sampled framebuffer");
  15270. }
  15271. this.bindUnboundFramebuffer(framebuffer);
  15272. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15273. var attachments = [];
  15274. for (var i = 0; i < textures.length; i++) {
  15275. var texture = textures[i];
  15276. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15277. var colorRenderbuffer = gl.createRenderbuffer();
  15278. if (!colorRenderbuffer) {
  15279. throw new Error("Unable to create multi sampled framebuffer");
  15280. }
  15281. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15282. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15283. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15284. texture._MSAAFramebuffer = framebuffer;
  15285. texture._MSAARenderBuffer = colorRenderbuffer;
  15286. texture.samples = samples;
  15287. texture._depthStencilBuffer = depthStencilBuffer;
  15288. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15289. attachments.push(attachment);
  15290. }
  15291. gl.drawBuffers(attachments);
  15292. }
  15293. else {
  15294. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15295. }
  15296. this.bindUnboundFramebuffer(null);
  15297. return samples;
  15298. };
  15299. /** @ignore */
  15300. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15301. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15302. };
  15303. /** @ignore */
  15304. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15305. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15306. };
  15307. /**
  15308. * Creates a new render target cube texture
  15309. * @param size defines the size of the texture
  15310. * @param options defines the options used to create the texture
  15311. * @returns a new render target cube texture stored in an InternalTexture
  15312. */
  15313. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15314. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15315. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15316. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15317. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15318. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15319. }
  15320. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15321. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15322. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15323. }
  15324. var gl = this._gl;
  15325. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15326. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15327. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15328. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15329. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15330. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15331. }
  15332. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15336. for (var face = 0; face < 6; face++) {
  15337. 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);
  15338. }
  15339. // Create the framebuffer
  15340. var framebuffer = gl.createFramebuffer();
  15341. this.bindUnboundFramebuffer(framebuffer);
  15342. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15343. // MipMaps
  15344. if (fullOptions.generateMipMaps) {
  15345. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15346. }
  15347. // Unbind
  15348. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15349. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15350. this.bindUnboundFramebuffer(null);
  15351. texture._framebuffer = framebuffer;
  15352. texture.width = size;
  15353. texture.height = size;
  15354. texture.isReady = true;
  15355. texture.isCube = true;
  15356. texture.samples = 1;
  15357. texture.generateMipMaps = fullOptions.generateMipMaps;
  15358. texture.samplingMode = fullOptions.samplingMode;
  15359. texture.type = fullOptions.type;
  15360. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15361. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15362. this._internalTexturesCache.push(texture);
  15363. return texture;
  15364. };
  15365. /**
  15366. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15367. * @param rootUrl defines the url where the file to load is located
  15368. * @param scene defines the current scene
  15369. * @param scale defines scale to apply to the mip map selection
  15370. * @param offset defines offset to apply to the mip map selection
  15371. * @param onLoad defines an optional callback raised when the texture is loaded
  15372. * @param onError defines an optional callback raised if there is an issue to load the texture
  15373. * @param format defines the format of the data
  15374. * @param forcedExtension defines the extension to use to pick the right loader
  15375. * @returns the cube texture as an InternalTexture
  15376. */
  15377. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15378. var _this = this;
  15379. if (onLoad === void 0) { onLoad = null; }
  15380. if (onError === void 0) { onError = null; }
  15381. if (forcedExtension === void 0) { forcedExtension = null; }
  15382. var callback = function (loadData) {
  15383. if (!loadData) {
  15384. if (onLoad) {
  15385. onLoad(null);
  15386. }
  15387. return;
  15388. }
  15389. var texture = loadData.texture;
  15390. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15391. texture._lodGenerationScale = scale;
  15392. texture._lodGenerationOffset = offset;
  15393. if (_this._caps.textureLOD) {
  15394. // Do not add extra process if texture lod is supported.
  15395. if (onLoad) {
  15396. onLoad(texture);
  15397. }
  15398. return;
  15399. }
  15400. var mipSlices = 3;
  15401. var gl = _this._gl;
  15402. var width = loadData.width;
  15403. if (!width) {
  15404. return;
  15405. }
  15406. var textures = [];
  15407. for (var i = 0; i < mipSlices; i++) {
  15408. //compute LOD from even spacing in smoothness (matching shader calculation)
  15409. var smoothness = i / (mipSlices - 1);
  15410. var roughness = 1 - smoothness;
  15411. var minLODIndex = offset; // roughness = 0
  15412. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15413. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15414. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15415. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15416. glTextureFromLod.isCube = true;
  15417. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15422. if (loadData.isDDS) {
  15423. var info = loadData.info;
  15424. var data = loadData.data;
  15425. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15426. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15427. }
  15428. else {
  15429. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15430. }
  15431. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15432. // Wrap in a base texture for easy binding.
  15433. var lodTexture = new BABYLON.BaseTexture(scene);
  15434. lodTexture.isCube = true;
  15435. lodTexture._texture = glTextureFromLod;
  15436. glTextureFromLod.isReady = true;
  15437. textures.push(lodTexture);
  15438. }
  15439. texture._lodTextureHigh = textures[2];
  15440. texture._lodTextureMid = textures[1];
  15441. texture._lodTextureLow = textures[0];
  15442. if (onLoad) {
  15443. onLoad(texture);
  15444. }
  15445. };
  15446. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15447. };
  15448. /**
  15449. * Creates a cube texture
  15450. * @param rootUrl defines the url where the files to load is located
  15451. * @param scene defines the current scene
  15452. * @param files defines the list of files to load (1 per face)
  15453. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15454. * @param onLoad defines an optional callback raised when the texture is loaded
  15455. * @param onError defines an optional callback raised if there is an issue to load the texture
  15456. * @param format defines the format of the data
  15457. * @param forcedExtension defines the extension to use to pick the right loader
  15458. * @returns the cube texture as an InternalTexture
  15459. */
  15460. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15461. var _this = this;
  15462. if (onLoad === void 0) { onLoad = null; }
  15463. if (onError === void 0) { onError = null; }
  15464. if (forcedExtension === void 0) { forcedExtension = null; }
  15465. var gl = this._gl;
  15466. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15467. texture.isCube = true;
  15468. texture.url = rootUrl;
  15469. texture.generateMipMaps = !noMipmap;
  15470. if (!this._doNotHandleContextLost) {
  15471. texture._extension = forcedExtension;
  15472. texture._files = files;
  15473. }
  15474. var isKTX = false;
  15475. var isDDS = false;
  15476. var lastDot = rootUrl.lastIndexOf('.');
  15477. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15478. if (this._textureFormatInUse) {
  15479. extension = this._textureFormatInUse;
  15480. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15481. isKTX = true;
  15482. }
  15483. else {
  15484. isDDS = (extension === ".dds");
  15485. }
  15486. var onerror = function (request, exception) {
  15487. if (onError && request) {
  15488. onError(request.status + " " + request.statusText, exception);
  15489. }
  15490. };
  15491. if (isKTX) {
  15492. this._loadFile(rootUrl, function (data) {
  15493. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15494. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15495. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15496. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15497. ktx.uploadLevels(_this._gl, !noMipmap);
  15498. _this.setCubeMapTextureParams(gl, loadMipmap);
  15499. texture.width = ktx.pixelWidth;
  15500. texture.height = ktx.pixelHeight;
  15501. texture.isReady = true;
  15502. }, undefined, undefined, true, onerror);
  15503. }
  15504. else if (isDDS) {
  15505. if (files && files.length === 6) {
  15506. this._cascadeLoadFiles(scene, function (imgs) {
  15507. var info;
  15508. var loadMipmap = false;
  15509. var width = 0;
  15510. for (var index = 0; index < imgs.length; index++) {
  15511. var data = imgs[index];
  15512. info = BABYLON.DDSTools.GetDDSInfo(data);
  15513. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15514. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15515. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15516. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15517. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15518. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15519. }
  15520. texture.width = info.width;
  15521. texture.height = info.height;
  15522. texture.type = info.textureType;
  15523. width = info.width;
  15524. }
  15525. _this.setCubeMapTextureParams(gl, loadMipmap);
  15526. texture.isReady = true;
  15527. if (onLoad) {
  15528. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15529. }
  15530. }, files, onError);
  15531. }
  15532. else {
  15533. this._loadFile(rootUrl, function (data) {
  15534. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15535. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15536. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15537. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15538. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15539. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15540. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15541. }
  15542. _this.setCubeMapTextureParams(gl, loadMipmap);
  15543. texture.width = info.width;
  15544. texture.height = info.height;
  15545. texture.isReady = true;
  15546. texture.type = info.textureType;
  15547. if (onLoad) {
  15548. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15549. }
  15550. }, undefined, undefined, true, onerror);
  15551. }
  15552. }
  15553. else {
  15554. if (!files) {
  15555. throw new Error("Cannot load cubemap because files were not defined");
  15556. }
  15557. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15558. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15559. var height = width;
  15560. _this._prepareWorkingCanvas();
  15561. if (!_this._workingCanvas || !_this._workingContext) {
  15562. return;
  15563. }
  15564. _this._workingCanvas.width = width;
  15565. _this._workingCanvas.height = height;
  15566. var faces = [
  15567. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15568. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15569. ];
  15570. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15572. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15573. for (var index = 0; index < faces.length; index++) {
  15574. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15575. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15576. }
  15577. if (!noMipmap) {
  15578. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15579. }
  15580. _this.setCubeMapTextureParams(gl, !noMipmap);
  15581. texture.width = width;
  15582. texture.height = height;
  15583. texture.isReady = true;
  15584. if (format) {
  15585. texture.format = format;
  15586. }
  15587. texture.onLoadedObservable.notifyObservers(texture);
  15588. texture.onLoadedObservable.clear();
  15589. if (onLoad) {
  15590. onLoad();
  15591. }
  15592. }, files, onError);
  15593. }
  15594. this._internalTexturesCache.push(texture);
  15595. return texture;
  15596. };
  15597. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15602. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15603. // this.resetTextureCache();
  15604. };
  15605. /**
  15606. * Update a raw cube texture
  15607. * @param texture defines the texture to udpdate
  15608. * @param data defines the data to store
  15609. * @param format defines the data format
  15610. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15611. * @param invertY defines if data must be stored with Y axis inverted
  15612. * @param compression defines the compression used (null by default)
  15613. * @param level defines which level of the texture to update
  15614. */
  15615. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15616. if (compression === void 0) { compression = null; }
  15617. if (level === void 0) { level = 0; }
  15618. texture._bufferViewArray = data;
  15619. texture.format = format;
  15620. texture.type = type;
  15621. texture.invertY = invertY;
  15622. texture._compression = compression;
  15623. var gl = this._gl;
  15624. var textureType = this._getWebGLTextureType(type);
  15625. var internalFormat = this._getInternalFormat(format);
  15626. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15627. var needConversion = false;
  15628. if (internalFormat === gl.RGB) {
  15629. internalFormat = gl.RGBA;
  15630. needConversion = true;
  15631. }
  15632. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15633. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15634. if (texture.width % 4 !== 0) {
  15635. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15636. }
  15637. // Data are known to be in +X +Y +Z -X -Y -Z
  15638. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15639. var faceData = data[faceIndex];
  15640. if (compression) {
  15641. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15642. }
  15643. else {
  15644. if (needConversion) {
  15645. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15646. }
  15647. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15648. }
  15649. }
  15650. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15651. if (isPot && texture.generateMipMaps && level === 0) {
  15652. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15653. }
  15654. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15655. // this.resetTextureCache();
  15656. texture.isReady = true;
  15657. };
  15658. /**
  15659. * Creates a new raw cube texture
  15660. * @param data defines the array of data to use to create each face
  15661. * @param size defines the size of the textures
  15662. * @param format defines the format of the data
  15663. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15664. * @param generateMipMaps defines if the engine should generate the mip levels
  15665. * @param invertY defines if data must be stored with Y axis inverted
  15666. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15667. * @param compression defines the compression used (null by default)
  15668. * @returns the cube texture as an InternalTexture
  15669. */
  15670. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15671. if (compression === void 0) { compression = null; }
  15672. var gl = this._gl;
  15673. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15674. texture.isCube = true;
  15675. texture.generateMipMaps = generateMipMaps;
  15676. texture.format = format;
  15677. texture.type = type;
  15678. if (!this._doNotHandleContextLost) {
  15679. texture._bufferViewArray = data;
  15680. }
  15681. var textureType = this._getWebGLTextureType(type);
  15682. var internalFormat = this._getInternalFormat(format);
  15683. if (internalFormat === gl.RGB) {
  15684. internalFormat = gl.RGBA;
  15685. }
  15686. var width = size;
  15687. var height = width;
  15688. texture.width = width;
  15689. texture.height = height;
  15690. // Double check on POT to generate Mips.
  15691. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15692. if (!isPot) {
  15693. generateMipMaps = false;
  15694. }
  15695. // Upload data if needed. The texture won't be ready until then.
  15696. if (data) {
  15697. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15698. }
  15699. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15700. // Filters
  15701. if (data && generateMipMaps) {
  15702. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15703. }
  15704. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15707. }
  15708. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15711. }
  15712. else {
  15713. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15714. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15716. }
  15717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15719. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15720. return texture;
  15721. };
  15722. /**
  15723. * Creates a new raw cube texture from a specified url
  15724. * @param url defines the url where the data is located
  15725. * @param scene defines the current scene
  15726. * @param size defines the size of the textures
  15727. * @param format defines the format of the data
  15728. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15729. * @param noMipmap defines if the engine should avoid generating the mip levels
  15730. * @param callback defines a callback used to extract texture data from loaded data
  15731. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15732. * @param onLoad defines a callback called when texture is loaded
  15733. * @param onError defines a callback called if there is an error
  15734. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15735. * @param invertY defines if data must be stored with Y axis inverted
  15736. * @returns the cube texture as an InternalTexture
  15737. */
  15738. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15739. var _this = this;
  15740. if (onLoad === void 0) { onLoad = null; }
  15741. if (onError === void 0) { onError = null; }
  15742. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15743. if (invertY === void 0) { invertY = false; }
  15744. var gl = this._gl;
  15745. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15746. scene._addPendingData(texture);
  15747. texture.url = url;
  15748. this._internalTexturesCache.push(texture);
  15749. var onerror = function (request, exception) {
  15750. scene._removePendingData(texture);
  15751. if (onError && request) {
  15752. onError(request.status + " " + request.statusText, exception);
  15753. }
  15754. };
  15755. var internalCallback = function (data) {
  15756. var width = texture.width;
  15757. var faceDataArrays = callback(data);
  15758. if (!faceDataArrays) {
  15759. return;
  15760. }
  15761. if (mipmapGenerator) {
  15762. var textureType = _this._getWebGLTextureType(type);
  15763. var internalFormat = _this._getInternalFormat(format);
  15764. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15765. var needConversion = false;
  15766. if (internalFormat === gl.RGB) {
  15767. internalFormat = gl.RGBA;
  15768. needConversion = true;
  15769. }
  15770. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15771. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15772. var mipData = mipmapGenerator(faceDataArrays);
  15773. for (var level = 0; level < mipData.length; level++) {
  15774. var mipSize = width >> level;
  15775. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15776. var mipFaceData = mipData[level][faceIndex];
  15777. if (needConversion) {
  15778. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15779. }
  15780. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15781. }
  15782. }
  15783. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15784. }
  15785. else {
  15786. texture.generateMipMaps = !noMipmap;
  15787. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15788. }
  15789. texture.isReady = true;
  15790. // this.resetTextureCache();
  15791. scene._removePendingData(texture);
  15792. if (onLoad) {
  15793. onLoad();
  15794. }
  15795. };
  15796. this._loadFile(url, function (data) {
  15797. internalCallback(data);
  15798. }, undefined, scene.database, true, onerror);
  15799. return texture;
  15800. };
  15801. ;
  15802. /**
  15803. * Update a raw 3D texture
  15804. * @param texture defines the texture to update
  15805. * @param data defines the data to store
  15806. * @param format defines the data format
  15807. * @param invertY defines if data must be stored with Y axis inverted
  15808. * @param compression defines the used compression (can be null)
  15809. */
  15810. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15811. if (compression === void 0) { compression = null; }
  15812. var internalFormat = this._getInternalFormat(format);
  15813. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15814. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15815. if (!this._doNotHandleContextLost) {
  15816. texture._bufferView = data;
  15817. texture.format = format;
  15818. texture.invertY = invertY;
  15819. texture._compression = compression;
  15820. }
  15821. if (texture.width % 4 !== 0) {
  15822. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15823. }
  15824. if (compression && data) {
  15825. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15826. }
  15827. else {
  15828. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15829. }
  15830. if (texture.generateMipMaps) {
  15831. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15832. }
  15833. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15834. // this.resetTextureCache();
  15835. texture.isReady = true;
  15836. };
  15837. /**
  15838. * Creates a new raw 3D texture
  15839. * @param data defines the data used to create the texture
  15840. * @param width defines the width of the texture
  15841. * @param height defines the height of the texture
  15842. * @param depth defines the depth of the texture
  15843. * @param format defines the format of the texture
  15844. * @param generateMipMaps defines if the engine must generate mip levels
  15845. * @param invertY defines if data must be stored with Y axis inverted
  15846. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15847. * @param compression defines the compressed used (can be null)
  15848. * @returns a new raw 3D texture (stored in an InternalTexture)
  15849. */
  15850. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15851. if (compression === void 0) { compression = null; }
  15852. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15853. texture.baseWidth = width;
  15854. texture.baseHeight = height;
  15855. texture.baseDepth = depth;
  15856. texture.width = width;
  15857. texture.height = height;
  15858. texture.depth = depth;
  15859. texture.format = format;
  15860. texture.generateMipMaps = generateMipMaps;
  15861. texture.samplingMode = samplingMode;
  15862. texture.is3D = true;
  15863. if (!this._doNotHandleContextLost) {
  15864. texture._bufferView = data;
  15865. }
  15866. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15867. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15868. // Filters
  15869. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15870. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15871. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15872. if (generateMipMaps) {
  15873. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15874. }
  15875. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15876. this._internalTexturesCache.push(texture);
  15877. return texture;
  15878. };
  15879. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15880. var gl = this._gl;
  15881. if (!gl) {
  15882. return;
  15883. }
  15884. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15887. if (!noMipmap && !isCompressed) {
  15888. gl.generateMipmap(gl.TEXTURE_2D);
  15889. }
  15890. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15891. // this.resetTextureCache();
  15892. if (scene) {
  15893. scene._removePendingData(texture);
  15894. }
  15895. texture.onLoadedObservable.notifyObservers(texture);
  15896. texture.onLoadedObservable.clear();
  15897. };
  15898. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15899. var _this = this;
  15900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15901. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15902. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15903. var gl = this._gl;
  15904. if (!gl) {
  15905. return;
  15906. }
  15907. if (!texture._webGLTexture) {
  15908. // this.resetTextureCache();
  15909. if (scene) {
  15910. scene._removePendingData(texture);
  15911. }
  15912. return;
  15913. }
  15914. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15915. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15916. texture.baseWidth = width;
  15917. texture.baseHeight = height;
  15918. texture.width = potWidth;
  15919. texture.height = potHeight;
  15920. texture.isReady = true;
  15921. if (processFunction(potWidth, potHeight, function () {
  15922. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15923. })) {
  15924. // Returning as texture needs extra async steps
  15925. return;
  15926. }
  15927. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15928. };
  15929. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15930. // Create new RGBA data container.
  15931. var rgbaData;
  15932. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15933. rgbaData = new Float32Array(width * height * 4);
  15934. }
  15935. else {
  15936. rgbaData = new Uint32Array(width * height * 4);
  15937. }
  15938. // Convert each pixel.
  15939. for (var x = 0; x < width; x++) {
  15940. for (var y = 0; y < height; y++) {
  15941. var index = (y * width + x) * 3;
  15942. var newIndex = (y * width + x) * 4;
  15943. // Map Old Value to new value.
  15944. rgbaData[newIndex + 0] = rgbData[index + 0];
  15945. rgbaData[newIndex + 1] = rgbData[index + 1];
  15946. rgbaData[newIndex + 2] = rgbData[index + 2];
  15947. // Add fully opaque alpha channel.
  15948. rgbaData[newIndex + 3] = 1;
  15949. }
  15950. }
  15951. return rgbaData;
  15952. };
  15953. /** @ignore */
  15954. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15955. var gl = this._gl;
  15956. if (texture._framebuffer) {
  15957. gl.deleteFramebuffer(texture._framebuffer);
  15958. texture._framebuffer = null;
  15959. }
  15960. if (texture._depthStencilBuffer) {
  15961. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15962. texture._depthStencilBuffer = null;
  15963. }
  15964. if (texture._MSAAFramebuffer) {
  15965. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15966. texture._MSAAFramebuffer = null;
  15967. }
  15968. if (texture._MSAARenderBuffer) {
  15969. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15970. texture._MSAARenderBuffer = null;
  15971. }
  15972. };
  15973. /** @ignore */
  15974. Engine.prototype._releaseTexture = function (texture) {
  15975. var gl = this._gl;
  15976. this._releaseFramebufferObjects(texture);
  15977. gl.deleteTexture(texture._webGLTexture);
  15978. // Unbind channels
  15979. this.unbindAllTextures();
  15980. var index = this._internalTexturesCache.indexOf(texture);
  15981. if (index !== -1) {
  15982. this._internalTexturesCache.splice(index, 1);
  15983. }
  15984. // Integrated fixed lod samplers.
  15985. if (texture._lodTextureHigh) {
  15986. texture._lodTextureHigh.dispose();
  15987. }
  15988. if (texture._lodTextureMid) {
  15989. texture._lodTextureMid.dispose();
  15990. }
  15991. if (texture._lodTextureLow) {
  15992. texture._lodTextureLow.dispose();
  15993. }
  15994. // Set output texture of post process to null if the texture has been released/disposed
  15995. this.scenes.forEach(function (scene) {
  15996. scene.postProcesses.forEach(function (postProcess) {
  15997. if (postProcess._outputTexture == texture) {
  15998. postProcess._outputTexture = null;
  15999. }
  16000. });
  16001. scene.cameras.forEach(function (camera) {
  16002. camera._postProcesses.forEach(function (postProcess) {
  16003. if (postProcess) {
  16004. if (postProcess._outputTexture == texture) {
  16005. postProcess._outputTexture = null;
  16006. }
  16007. }
  16008. });
  16009. });
  16010. });
  16011. };
  16012. Engine.prototype.setProgram = function (program) {
  16013. if (this._currentProgram !== program) {
  16014. this._gl.useProgram(program);
  16015. this._currentProgram = program;
  16016. }
  16017. };
  16018. /**
  16019. * Binds an effect to the webGL context
  16020. * @param effect defines the effect to bind
  16021. */
  16022. Engine.prototype.bindSamplers = function (effect) {
  16023. this.setProgram(effect.getProgram());
  16024. var samplers = effect.getSamplers();
  16025. for (var index = 0; index < samplers.length; index++) {
  16026. var uniform = effect.getUniform(samplers[index]);
  16027. if (uniform) {
  16028. this._boundUniforms[index] = uniform;
  16029. }
  16030. }
  16031. this._currentEffect = null;
  16032. };
  16033. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16034. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16035. return;
  16036. }
  16037. // Remove
  16038. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16039. // Bind last to it
  16040. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16041. // Bind to dummy
  16042. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16043. };
  16044. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16045. if (!internalTexture) {
  16046. return -1;
  16047. }
  16048. internalTexture._initialSlot = channel;
  16049. if (this.disableTextureBindingOptimization) {
  16050. if (channel !== internalTexture._designatedSlot) {
  16051. this._textureCollisions.addCount(1, false);
  16052. }
  16053. }
  16054. else {
  16055. if (channel !== internalTexture._designatedSlot) {
  16056. if (internalTexture._designatedSlot > -1) {
  16057. return internalTexture._designatedSlot;
  16058. }
  16059. else {
  16060. // No slot for this texture, let's pick a new one (if we find a free slot)
  16061. if (this._nextFreeTextureSlots.length) {
  16062. return this._nextFreeTextureSlots[0];
  16063. }
  16064. // We need to recycle the oldest bound texture, sorry.
  16065. this._textureCollisions.addCount(1, false);
  16066. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16067. }
  16068. }
  16069. }
  16070. return channel;
  16071. };
  16072. Engine.prototype._linkTrackers = function (previous, next) {
  16073. previous.next = next;
  16074. next.previous = previous;
  16075. };
  16076. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16077. var currentSlot = internalTexture._designatedSlot;
  16078. if (currentSlot === -1) {
  16079. return -1;
  16080. }
  16081. internalTexture._designatedSlot = -1;
  16082. if (this.disableTextureBindingOptimization) {
  16083. return -1;
  16084. }
  16085. // Remove from bound list
  16086. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16087. // Free the slot
  16088. this._boundTexturesCache[currentSlot] = null;
  16089. this._nextFreeTextureSlots.push(currentSlot);
  16090. return currentSlot;
  16091. };
  16092. Engine.prototype._activateCurrentTexture = function () {
  16093. if (this._currentTextureChannel !== this._activeChannel) {
  16094. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16095. this._currentTextureChannel = this._activeChannel;
  16096. }
  16097. };
  16098. /** @ignore */
  16099. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16100. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16101. if (force === void 0) { force = false; }
  16102. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16103. this._activeChannel = texture._designatedSlot;
  16104. }
  16105. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16106. var isTextureForRendering = texture && texture._initialSlot > -1;
  16107. if (currentTextureBound !== texture || force) {
  16108. if (currentTextureBound) {
  16109. this._removeDesignatedSlot(currentTextureBound);
  16110. }
  16111. this._activateCurrentTexture();
  16112. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16113. this._boundTexturesCache[this._activeChannel] = texture;
  16114. if (texture) {
  16115. if (!this.disableTextureBindingOptimization) {
  16116. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16117. if (slotIndex > -1) {
  16118. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16119. }
  16120. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16121. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16122. }
  16123. texture._designatedSlot = this._activeChannel;
  16124. }
  16125. }
  16126. else if (forTextureDataUpdate) {
  16127. this._activateCurrentTexture();
  16128. }
  16129. if (isTextureForRendering && !forTextureDataUpdate) {
  16130. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16131. }
  16132. };
  16133. /** @ignore */
  16134. Engine.prototype._bindTexture = function (channel, texture) {
  16135. if (channel < 0) {
  16136. return;
  16137. }
  16138. if (texture) {
  16139. channel = this._getCorrectTextureChannel(channel, texture);
  16140. }
  16141. this._activeChannel = channel;
  16142. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16143. };
  16144. /**
  16145. * Sets a texture to the webGL context from a postprocess
  16146. * @param channel defines the channel to use
  16147. * @param postProcess defines the source postprocess
  16148. */
  16149. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16150. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16151. };
  16152. /**
  16153. * Binds the output of the passed in post process to the texture channel specified
  16154. * @param channel The channel the texture should be bound to
  16155. * @param postProcess The post process which's output should be bound
  16156. */
  16157. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16158. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16159. };
  16160. /**
  16161. * Unbind all textures from the webGL context
  16162. */
  16163. Engine.prototype.unbindAllTextures = function () {
  16164. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16165. this._activeChannel = channel;
  16166. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16167. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16168. if (this.webGLVersion > 1) {
  16169. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16170. }
  16171. }
  16172. };
  16173. /**
  16174. * Sets a texture to the according uniform.
  16175. * @param channel The texture channel
  16176. * @param uniform The uniform to set
  16177. * @param texture The texture to apply
  16178. */
  16179. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16180. if (channel < 0) {
  16181. return;
  16182. }
  16183. if (uniform) {
  16184. this._boundUniforms[channel] = uniform;
  16185. }
  16186. this._setTexture(channel, texture);
  16187. };
  16188. /**
  16189. * Sets a depth stencil texture from a render target to the according uniform.
  16190. * @param channel The texture channel
  16191. * @param uniform The uniform to set
  16192. * @param texture The render target texture containing the depth stencil texture to apply
  16193. */
  16194. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16195. if (channel < 0) {
  16196. return;
  16197. }
  16198. if (uniform) {
  16199. this._boundUniforms[channel] = uniform;
  16200. }
  16201. if (!texture || !texture.depthStencilTexture) {
  16202. this._setTexture(channel, null);
  16203. }
  16204. else {
  16205. this._setTexture(channel, texture, false, true);
  16206. }
  16207. };
  16208. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16209. var uniform = this._boundUniforms[sourceSlot];
  16210. if (uniform._currentState === destination) {
  16211. return;
  16212. }
  16213. this._gl.uniform1i(uniform, destination);
  16214. uniform._currentState = destination;
  16215. };
  16216. Engine.prototype._getTextureWrapMode = function (mode) {
  16217. switch (mode) {
  16218. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16219. return this._gl.REPEAT;
  16220. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16221. return this._gl.CLAMP_TO_EDGE;
  16222. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16223. return this._gl.MIRRORED_REPEAT;
  16224. }
  16225. return this._gl.REPEAT;
  16226. };
  16227. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16228. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16229. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16230. // Not ready?
  16231. if (!texture) {
  16232. if (this._boundTexturesCache[channel] != null) {
  16233. this._activeChannel = channel;
  16234. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16235. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16236. if (this.webGLVersion > 1) {
  16237. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16238. }
  16239. }
  16240. return false;
  16241. }
  16242. // Video
  16243. if (texture.video) {
  16244. this._activeChannel = channel;
  16245. texture.update();
  16246. }
  16247. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  16248. texture.delayLoad();
  16249. return false;
  16250. }
  16251. var internalTexture;
  16252. if (depthStencilTexture) {
  16253. internalTexture = texture.depthStencilTexture;
  16254. }
  16255. else if (texture.isReady()) {
  16256. internalTexture = texture.getInternalTexture();
  16257. }
  16258. else if (texture.isCube) {
  16259. internalTexture = this.emptyCubeTexture;
  16260. }
  16261. else if (texture.is3D) {
  16262. internalTexture = this.emptyTexture3D;
  16263. }
  16264. else {
  16265. internalTexture = this.emptyTexture;
  16266. }
  16267. if (!isPartOfTextureArray) {
  16268. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16269. }
  16270. var needToBind = true;
  16271. if (this._boundTexturesCache[channel] === internalTexture) {
  16272. this._moveBoundTextureOnTop(internalTexture);
  16273. if (!isPartOfTextureArray) {
  16274. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16275. }
  16276. needToBind = false;
  16277. }
  16278. this._activeChannel = channel;
  16279. if (internalTexture && internalTexture.is3D) {
  16280. if (needToBind) {
  16281. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16282. }
  16283. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16284. internalTexture._cachedWrapU = texture.wrapU;
  16285. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16286. }
  16287. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16288. internalTexture._cachedWrapV = texture.wrapV;
  16289. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16290. }
  16291. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16292. internalTexture._cachedWrapR = texture.wrapR;
  16293. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16294. }
  16295. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16296. }
  16297. else if (internalTexture && internalTexture.isCube) {
  16298. if (needToBind) {
  16299. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16300. }
  16301. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16302. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16303. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16304. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16305. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16306. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16307. }
  16308. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16309. }
  16310. else {
  16311. if (needToBind) {
  16312. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16313. }
  16314. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16315. internalTexture._cachedWrapU = texture.wrapU;
  16316. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16317. }
  16318. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16319. internalTexture._cachedWrapV = texture.wrapV;
  16320. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16321. }
  16322. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16323. }
  16324. return true;
  16325. };
  16326. /**
  16327. * Sets an array of texture to the webGL context
  16328. * @param channel defines the channel where the texture array must be set
  16329. * @param uniform defines the associated uniform location
  16330. * @param textures defines the array of textures to bind
  16331. */
  16332. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16333. if (channel < 0 || !uniform) {
  16334. return;
  16335. }
  16336. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16337. this._textureUnits = new Int32Array(textures.length);
  16338. }
  16339. for (var i = 0; i < textures.length; i++) {
  16340. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16341. }
  16342. this._gl.uniform1iv(uniform, this._textureUnits);
  16343. for (var index = 0; index < textures.length; index++) {
  16344. this._setTexture(this._textureUnits[index], textures[index], true);
  16345. }
  16346. };
  16347. /** @ignore */
  16348. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16349. var internalTexture = texture.getInternalTexture();
  16350. if (!internalTexture) {
  16351. return;
  16352. }
  16353. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16354. var value = texture.anisotropicFilteringLevel;
  16355. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16356. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16357. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16358. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16359. }
  16360. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16361. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16362. internalTexture._cachedAnisotropicFilteringLevel = value;
  16363. }
  16364. };
  16365. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16366. this._bindTextureDirectly(target, texture, true, true);
  16367. this._gl.texParameterf(target, parameter, value);
  16368. };
  16369. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16370. if (texture) {
  16371. this._bindTextureDirectly(target, texture, true, true);
  16372. }
  16373. this._gl.texParameteri(target, parameter, value);
  16374. };
  16375. /**
  16376. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16377. * @param x defines the x coordinate of the rectangle where pixels must be read
  16378. * @param y defines the y coordinate of the rectangle where pixels must be read
  16379. * @param width defines the width of the rectangle where pixels must be read
  16380. * @param height defines the height of the rectangle where pixels must be read
  16381. * @returns a Uint8Array containing RGBA colors
  16382. */
  16383. Engine.prototype.readPixels = function (x, y, width, height) {
  16384. var data = new Uint8Array(height * width * 4);
  16385. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16386. return data;
  16387. };
  16388. /**
  16389. * Add an externaly attached data from its key.
  16390. * This method call will fail and return false, if such key already exists.
  16391. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16392. * @param key the unique key that identifies the data
  16393. * @param data the data object to associate to the key for this Engine instance
  16394. * @return true if no such key were already present and the data was added successfully, false otherwise
  16395. */
  16396. Engine.prototype.addExternalData = function (key, data) {
  16397. if (!this._externalData) {
  16398. this._externalData = new BABYLON.StringDictionary();
  16399. }
  16400. return this._externalData.add(key, data);
  16401. };
  16402. /**
  16403. * Get an externaly attached data from its key
  16404. * @param key the unique key that identifies the data
  16405. * @return the associated data, if present (can be null), or undefined if not present
  16406. */
  16407. Engine.prototype.getExternalData = function (key) {
  16408. if (!this._externalData) {
  16409. this._externalData = new BABYLON.StringDictionary();
  16410. }
  16411. return this._externalData.get(key);
  16412. };
  16413. /**
  16414. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16415. * @param key the unique key that identifies the data
  16416. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16417. * @return the associated data, can be null if the factory returned null.
  16418. */
  16419. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16420. if (!this._externalData) {
  16421. this._externalData = new BABYLON.StringDictionary();
  16422. }
  16423. return this._externalData.getOrAddWithFactory(key, factory);
  16424. };
  16425. /**
  16426. * Remove an externaly attached data from the Engine instance
  16427. * @param key the unique key that identifies the data
  16428. * @return true if the data was successfully removed, false if it doesn't exist
  16429. */
  16430. Engine.prototype.removeExternalData = function (key) {
  16431. if (!this._externalData) {
  16432. this._externalData = new BABYLON.StringDictionary();
  16433. }
  16434. return this._externalData.remove(key);
  16435. };
  16436. /**
  16437. * Unbind all vertex attributes from the webGL context
  16438. */
  16439. Engine.prototype.unbindAllAttributes = function () {
  16440. if (this._mustWipeVertexAttributes) {
  16441. this._mustWipeVertexAttributes = false;
  16442. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16443. this._gl.disableVertexAttribArray(i);
  16444. this._vertexAttribArraysEnabled[i] = false;
  16445. this._currentBufferPointers[i].active = false;
  16446. }
  16447. return;
  16448. }
  16449. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16450. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16451. continue;
  16452. }
  16453. this._gl.disableVertexAttribArray(i);
  16454. this._vertexAttribArraysEnabled[i] = false;
  16455. this._currentBufferPointers[i].active = false;
  16456. }
  16457. };
  16458. /**
  16459. * 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
  16460. */
  16461. Engine.prototype.releaseEffects = function () {
  16462. for (var name in this._compiledEffects) {
  16463. this._deleteProgram(this._compiledEffects[name]._program);
  16464. }
  16465. this._compiledEffects = {};
  16466. };
  16467. /**
  16468. * Dispose and release all associated resources
  16469. */
  16470. Engine.prototype.dispose = function () {
  16471. this.hideLoadingUI();
  16472. this.stopRenderLoop();
  16473. // Release postProcesses
  16474. while (this.postProcesses.length) {
  16475. this.postProcesses[0].dispose();
  16476. }
  16477. // Empty texture
  16478. if (this._emptyTexture) {
  16479. this._releaseTexture(this._emptyTexture);
  16480. this._emptyTexture = null;
  16481. }
  16482. if (this._emptyCubeTexture) {
  16483. this._releaseTexture(this._emptyCubeTexture);
  16484. this._emptyCubeTexture = null;
  16485. }
  16486. // Rescale PP
  16487. if (this._rescalePostProcess) {
  16488. this._rescalePostProcess.dispose();
  16489. }
  16490. // Release scenes
  16491. while (this.scenes.length) {
  16492. this.scenes[0].dispose();
  16493. }
  16494. // Release audio engine
  16495. if (Engine.audioEngine) {
  16496. Engine.audioEngine.dispose();
  16497. }
  16498. // Release effects
  16499. this.releaseEffects();
  16500. // Unbind
  16501. this.unbindAllAttributes();
  16502. this._boundUniforms = [];
  16503. if (this._dummyFramebuffer) {
  16504. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16505. }
  16506. //WebVR
  16507. this.disableVR();
  16508. // Events
  16509. if (BABYLON.Tools.IsWindowObjectExist()) {
  16510. window.removeEventListener("blur", this._onBlur);
  16511. window.removeEventListener("focus", this._onFocus);
  16512. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16513. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16514. if (this._renderingCanvas) {
  16515. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16516. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16517. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16518. if (!this._doNotHandleContextLost) {
  16519. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16520. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16521. }
  16522. }
  16523. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16524. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16525. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16526. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16527. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16528. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16529. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16530. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16531. if (this._onVrDisplayConnect) {
  16532. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16533. if (this._onVrDisplayDisconnect) {
  16534. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16535. }
  16536. if (this._onVrDisplayPresentChange) {
  16537. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16538. }
  16539. this._onVrDisplayConnect = null;
  16540. this._onVrDisplayDisconnect = null;
  16541. }
  16542. }
  16543. // Remove from Instances
  16544. var index = Engine.Instances.indexOf(this);
  16545. if (index >= 0) {
  16546. Engine.Instances.splice(index, 1);
  16547. }
  16548. this._workingCanvas = null;
  16549. this._workingContext = null;
  16550. this._currentBufferPointers = [];
  16551. this._renderingCanvas = null;
  16552. this._currentProgram = null;
  16553. this._bindedRenderFunction = null;
  16554. this.onResizeObservable.clear();
  16555. this.onCanvasBlurObservable.clear();
  16556. this.onCanvasFocusObservable.clear();
  16557. this.onCanvasPointerOutObservable.clear();
  16558. this.onBeginFrameObservable.clear();
  16559. this.onEndFrameObservable.clear();
  16560. BABYLON.Effect.ResetCache();
  16561. // Abort active requests
  16562. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16563. var request = _a[_i];
  16564. request.abort();
  16565. }
  16566. };
  16567. // Loading screen
  16568. /**
  16569. * Display the loading screen
  16570. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16571. */
  16572. Engine.prototype.displayLoadingUI = function () {
  16573. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16574. return;
  16575. }
  16576. var loadingScreen = this.loadingScreen;
  16577. if (loadingScreen) {
  16578. loadingScreen.displayLoadingUI();
  16579. }
  16580. };
  16581. /**
  16582. * Hide the loading screen
  16583. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16584. */
  16585. Engine.prototype.hideLoadingUI = function () {
  16586. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16587. return;
  16588. }
  16589. var loadingScreen = this.loadingScreen;
  16590. if (loadingScreen) {
  16591. loadingScreen.hideLoadingUI();
  16592. }
  16593. };
  16594. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16595. /**
  16596. * Gets the current loading screen object
  16597. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16598. */
  16599. get: function () {
  16600. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16601. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16602. return this._loadingScreen;
  16603. },
  16604. /**
  16605. * Sets the current loading screen object
  16606. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16607. */
  16608. set: function (loadingScreen) {
  16609. this._loadingScreen = loadingScreen;
  16610. },
  16611. enumerable: true,
  16612. configurable: true
  16613. });
  16614. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16615. /**
  16616. * Sets the current loading screen text
  16617. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16618. */
  16619. set: function (text) {
  16620. this.loadingScreen.loadingUIText = text;
  16621. },
  16622. enumerable: true,
  16623. configurable: true
  16624. });
  16625. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16626. /**
  16627. * Sets the current loading screen background color
  16628. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16629. */
  16630. set: function (color) {
  16631. this.loadingScreen.loadingUIBackgroundColor = color;
  16632. },
  16633. enumerable: true,
  16634. configurable: true
  16635. });
  16636. /**
  16637. * Attach a new callback raised when context lost event is fired
  16638. * @param callback defines the callback to call
  16639. */
  16640. Engine.prototype.attachContextLostEvent = function (callback) {
  16641. if (this._renderingCanvas) {
  16642. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16643. }
  16644. };
  16645. /**
  16646. * Attach a new callback raised when context restored event is fired
  16647. * @param callback defines the callback to call
  16648. */
  16649. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16650. if (this._renderingCanvas) {
  16651. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16652. }
  16653. };
  16654. /**
  16655. * Gets the source code of the vertex shader associated with a specific webGL program
  16656. * @param program defines the program to use
  16657. * @returns a string containing the source code of the vertex shader associated with the program
  16658. */
  16659. Engine.prototype.getVertexShaderSource = function (program) {
  16660. var shaders = this._gl.getAttachedShaders(program);
  16661. if (!shaders) {
  16662. return null;
  16663. }
  16664. return this._gl.getShaderSource(shaders[0]);
  16665. };
  16666. /**
  16667. * Gets the source code of the fragment shader associated with a specific webGL program
  16668. * @param program defines the program to use
  16669. * @returns a string containing the source code of the fragment shader associated with the program
  16670. */
  16671. Engine.prototype.getFragmentShaderSource = function (program) {
  16672. var shaders = this._gl.getAttachedShaders(program);
  16673. if (!shaders) {
  16674. return null;
  16675. }
  16676. return this._gl.getShaderSource(shaders[1]);
  16677. };
  16678. /**
  16679. * Get the current error code of the webGL context
  16680. * @returns the error code
  16681. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16682. */
  16683. Engine.prototype.getError = function () {
  16684. return this._gl.getError();
  16685. };
  16686. // FPS
  16687. /**
  16688. * Gets the current framerate
  16689. * @returns a number representing the framerate
  16690. */
  16691. Engine.prototype.getFps = function () {
  16692. return this._fps;
  16693. };
  16694. /**
  16695. * Gets the time spent between current and previous frame
  16696. * @returns a number representing the delta time in ms
  16697. */
  16698. Engine.prototype.getDeltaTime = function () {
  16699. return this._deltaTime;
  16700. };
  16701. Engine.prototype._measureFps = function () {
  16702. this._performanceMonitor.sampleFrame();
  16703. this._fps = this._performanceMonitor.averageFPS;
  16704. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16705. };
  16706. /** @ignore */
  16707. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16708. if (faceIndex === void 0) { faceIndex = -1; }
  16709. var gl = this._gl;
  16710. if (!this._dummyFramebuffer) {
  16711. var dummy = gl.createFramebuffer();
  16712. if (!dummy) {
  16713. throw new Error("Unable to create dummy framebuffer");
  16714. }
  16715. this._dummyFramebuffer = dummy;
  16716. }
  16717. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16718. if (faceIndex > -1) {
  16719. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16720. }
  16721. else {
  16722. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16723. }
  16724. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16725. var buffer;
  16726. switch (readType) {
  16727. case gl.UNSIGNED_BYTE:
  16728. buffer = new Uint8Array(4 * width * height);
  16729. readType = gl.UNSIGNED_BYTE;
  16730. break;
  16731. default:
  16732. buffer = new Float32Array(4 * width * height);
  16733. readType = gl.FLOAT;
  16734. break;
  16735. }
  16736. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16737. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16738. return buffer;
  16739. };
  16740. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16741. if (this._webGLVersion > 1) {
  16742. return this._caps.colorBufferFloat;
  16743. }
  16744. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16745. };
  16746. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16747. if (this._webGLVersion > 1) {
  16748. return this._caps.colorBufferFloat;
  16749. }
  16750. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16751. };
  16752. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16753. Engine.prototype._canRenderToFramebuffer = function (type) {
  16754. var gl = this._gl;
  16755. //clear existing errors
  16756. while (gl.getError() !== gl.NO_ERROR) { }
  16757. var successful = true;
  16758. var texture = gl.createTexture();
  16759. gl.bindTexture(gl.TEXTURE_2D, texture);
  16760. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16763. var fb = gl.createFramebuffer();
  16764. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16765. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16766. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16767. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16768. successful = successful && (gl.getError() === gl.NO_ERROR);
  16769. //try render by clearing frame buffer's color buffer
  16770. if (successful) {
  16771. gl.clear(gl.COLOR_BUFFER_BIT);
  16772. successful = successful && (gl.getError() === gl.NO_ERROR);
  16773. }
  16774. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16775. if (successful) {
  16776. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16777. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16778. var readFormat = gl.RGBA;
  16779. var readType = gl.UNSIGNED_BYTE;
  16780. var buffer = new Uint8Array(4);
  16781. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16782. successful = successful && (gl.getError() === gl.NO_ERROR);
  16783. }
  16784. //clean up
  16785. gl.deleteTexture(texture);
  16786. gl.deleteFramebuffer(fb);
  16787. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16788. //clear accumulated errors
  16789. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16790. return successful;
  16791. };
  16792. /** @ignore */
  16793. Engine.prototype._getWebGLTextureType = function (type) {
  16794. if (type === Engine.TEXTURETYPE_FLOAT) {
  16795. return this._gl.FLOAT;
  16796. }
  16797. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16798. // Add Half Float Constant.
  16799. return this._gl.HALF_FLOAT_OES;
  16800. }
  16801. return this._gl.UNSIGNED_BYTE;
  16802. };
  16803. ;
  16804. Engine.prototype._getInternalFormat = function (format) {
  16805. var internalFormat = this._gl.RGBA;
  16806. switch (format) {
  16807. case Engine.TEXTUREFORMAT_ALPHA:
  16808. internalFormat = this._gl.ALPHA;
  16809. break;
  16810. case Engine.TEXTUREFORMAT_LUMINANCE:
  16811. internalFormat = this._gl.LUMINANCE;
  16812. break;
  16813. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16814. internalFormat = this._gl.LUMINANCE_ALPHA;
  16815. break;
  16816. case Engine.TEXTUREFORMAT_RGB:
  16817. case Engine.TEXTUREFORMAT_RGB32F:
  16818. internalFormat = this._gl.RGB;
  16819. break;
  16820. case Engine.TEXTUREFORMAT_RGBA:
  16821. case Engine.TEXTUREFORMAT_RGBA32F:
  16822. internalFormat = this._gl.RGBA;
  16823. break;
  16824. case Engine.TEXTUREFORMAT_R32F:
  16825. internalFormat = this._gl.RED;
  16826. break;
  16827. case Engine.TEXTUREFORMAT_RG32F:
  16828. internalFormat = this._gl.RG;
  16829. break;
  16830. }
  16831. return internalFormat;
  16832. };
  16833. /** @ignore */
  16834. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16835. if (this._webGLVersion === 1) {
  16836. if (format) {
  16837. switch (format) {
  16838. case Engine.TEXTUREFORMAT_LUMINANCE:
  16839. return this._gl.LUMINANCE;
  16840. }
  16841. }
  16842. return this._gl.RGBA;
  16843. }
  16844. if (type === Engine.TEXTURETYPE_FLOAT) {
  16845. if (format) {
  16846. switch (format) {
  16847. case Engine.TEXTUREFORMAT_R32F:
  16848. return this._gl.R32F;
  16849. case Engine.TEXTUREFORMAT_RG32F:
  16850. return this._gl.RG32F;
  16851. case Engine.TEXTUREFORMAT_RGB32F:
  16852. return this._gl.RGB32F;
  16853. }
  16854. }
  16855. return this._gl.RGBA32F;
  16856. }
  16857. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16858. return this._gl.RGBA16F;
  16859. }
  16860. if (format) {
  16861. switch (format) {
  16862. case Engine.TEXTUREFORMAT_LUMINANCE:
  16863. return this._gl.LUMINANCE;
  16864. }
  16865. }
  16866. return this._gl.RGBA;
  16867. };
  16868. ;
  16869. /** @ignore */
  16870. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16871. if (type === Engine.TEXTURETYPE_FLOAT) {
  16872. return this._gl.RGBA32F;
  16873. }
  16874. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16875. return this._gl.RGBA16F;
  16876. }
  16877. return this._gl.RGBA8;
  16878. };
  16879. ;
  16880. /**
  16881. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16882. * @return the new query
  16883. */
  16884. Engine.prototype.createQuery = function () {
  16885. return this._gl.createQuery();
  16886. };
  16887. /**
  16888. * Delete and release a webGL query
  16889. * @param query defines the query to delete
  16890. * @return the current engine
  16891. */
  16892. Engine.prototype.deleteQuery = function (query) {
  16893. this._gl.deleteQuery(query);
  16894. return this;
  16895. };
  16896. /**
  16897. * Check if a given query has resolved and got its value
  16898. * @param query defines the query to check
  16899. * @returns true if the query got its value
  16900. */
  16901. Engine.prototype.isQueryResultAvailable = function (query) {
  16902. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16903. };
  16904. /**
  16905. * Gets the value of a given query
  16906. * @param query defines the query to check
  16907. * @returns the value of the query
  16908. */
  16909. Engine.prototype.getQueryResult = function (query) {
  16910. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16911. };
  16912. /**
  16913. * Initiates an occlusion query
  16914. * @param algorithmType defines the algorithm to use
  16915. * @param query defines the query to use
  16916. * @returns the current engine
  16917. * @see http://doc.babylonjs.com/features/occlusionquery
  16918. */
  16919. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16920. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16921. this._gl.beginQuery(glAlgorithm, query);
  16922. return this;
  16923. };
  16924. /**
  16925. * Ends an occlusion query
  16926. * @see http://doc.babylonjs.com/features/occlusionquery
  16927. * @param algorithmType defines the algorithm to use
  16928. * @returns the current engine
  16929. */
  16930. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16931. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16932. this._gl.endQuery(glAlgorithm);
  16933. return this;
  16934. };
  16935. /* Time queries */
  16936. Engine.prototype._createTimeQuery = function () {
  16937. var timerQuery = this._caps.timerQuery;
  16938. if (timerQuery.createQueryEXT) {
  16939. return timerQuery.createQueryEXT();
  16940. }
  16941. return this.createQuery();
  16942. };
  16943. Engine.prototype._deleteTimeQuery = function (query) {
  16944. var timerQuery = this._caps.timerQuery;
  16945. if (timerQuery.deleteQueryEXT) {
  16946. timerQuery.deleteQueryEXT(query);
  16947. return;
  16948. }
  16949. this.deleteQuery(query);
  16950. };
  16951. Engine.prototype._getTimeQueryResult = function (query) {
  16952. var timerQuery = this._caps.timerQuery;
  16953. if (timerQuery.getQueryObjectEXT) {
  16954. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16955. }
  16956. return this.getQueryResult(query);
  16957. };
  16958. Engine.prototype._getTimeQueryAvailability = function (query) {
  16959. var timerQuery = this._caps.timerQuery;
  16960. if (timerQuery.getQueryObjectEXT) {
  16961. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16962. }
  16963. return this.isQueryResultAvailable(query);
  16964. };
  16965. /**
  16966. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16967. * Please note that only one query can be issued at a time
  16968. * @returns a time token used to track the time span
  16969. */
  16970. Engine.prototype.startTimeQuery = function () {
  16971. var timerQuery = this._caps.timerQuery;
  16972. if (!timerQuery) {
  16973. return null;
  16974. }
  16975. var token = new BABYLON._TimeToken();
  16976. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16977. if (this._caps.canUseTimestampForTimerQuery) {
  16978. token._startTimeQuery = this._createTimeQuery();
  16979. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16980. }
  16981. else {
  16982. if (this._currentNonTimestampToken) {
  16983. return this._currentNonTimestampToken;
  16984. }
  16985. token._timeElapsedQuery = this._createTimeQuery();
  16986. if (timerQuery.beginQueryEXT) {
  16987. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16988. }
  16989. else {
  16990. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16991. }
  16992. this._currentNonTimestampToken = token;
  16993. }
  16994. return token;
  16995. };
  16996. /**
  16997. * Ends a time query
  16998. * @param token defines the token used to measure the time span
  16999. * @returns the time spent (in ns)
  17000. */
  17001. Engine.prototype.endTimeQuery = function (token) {
  17002. var timerQuery = this._caps.timerQuery;
  17003. if (!timerQuery || !token) {
  17004. return -1;
  17005. }
  17006. if (this._caps.canUseTimestampForTimerQuery) {
  17007. if (!token._startTimeQuery) {
  17008. return -1;
  17009. }
  17010. if (!token._endTimeQuery) {
  17011. token._endTimeQuery = this._createTimeQuery();
  17012. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17013. }
  17014. }
  17015. else if (!token._timeElapsedQueryEnded) {
  17016. if (!token._timeElapsedQuery) {
  17017. return -1;
  17018. }
  17019. if (timerQuery.endQueryEXT) {
  17020. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17021. }
  17022. else {
  17023. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17024. }
  17025. token._timeElapsedQueryEnded = true;
  17026. }
  17027. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17028. var available = false;
  17029. if (token._endTimeQuery) {
  17030. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17031. }
  17032. else if (token._timeElapsedQuery) {
  17033. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17034. }
  17035. if (available && !disjoint) {
  17036. var result = 0;
  17037. if (this._caps.canUseTimestampForTimerQuery) {
  17038. if (!token._startTimeQuery || !token._endTimeQuery) {
  17039. return -1;
  17040. }
  17041. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17042. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17043. result = timeEnd - timeStart;
  17044. this._deleteTimeQuery(token._startTimeQuery);
  17045. this._deleteTimeQuery(token._endTimeQuery);
  17046. token._startTimeQuery = null;
  17047. token._endTimeQuery = null;
  17048. }
  17049. else {
  17050. if (!token._timeElapsedQuery) {
  17051. return -1;
  17052. }
  17053. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17054. this._deleteTimeQuery(token._timeElapsedQuery);
  17055. token._timeElapsedQuery = null;
  17056. token._timeElapsedQueryEnded = false;
  17057. this._currentNonTimestampToken = null;
  17058. }
  17059. return result;
  17060. }
  17061. return -1;
  17062. };
  17063. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17064. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17065. };
  17066. // Transform feedback
  17067. /**
  17068. * Creates a webGL transform feedback object
  17069. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17070. * @returns the webGL transform feedback object
  17071. */
  17072. Engine.prototype.createTransformFeedback = function () {
  17073. return this._gl.createTransformFeedback();
  17074. };
  17075. /**
  17076. * Delete a webGL transform feedback object
  17077. * @param value defines the webGL transform feedback object to delete
  17078. */
  17079. Engine.prototype.deleteTransformFeedback = function (value) {
  17080. this._gl.deleteTransformFeedback(value);
  17081. };
  17082. /**
  17083. * Bind a webGL transform feedback object to the webgl context
  17084. * @param value defines the webGL transform feedback object to bind
  17085. */
  17086. Engine.prototype.bindTransformFeedback = function (value) {
  17087. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17088. };
  17089. /**
  17090. * Begins a transform feedback operation
  17091. * @param usePoints defines if points or triangles must be used
  17092. */
  17093. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17094. if (usePoints === void 0) { usePoints = true; }
  17095. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17096. };
  17097. /**
  17098. * Ends a transform feedback operation
  17099. */
  17100. Engine.prototype.endTransformFeedback = function () {
  17101. this._gl.endTransformFeedback();
  17102. };
  17103. /**
  17104. * Specify the varyings to use with transform feedback
  17105. * @param program defines the associated webGL program
  17106. * @param value defines the list of strings representing the varying names
  17107. */
  17108. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17109. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17110. };
  17111. /**
  17112. * Bind a webGL buffer for a transform feedback operation
  17113. * @param value defines the webGL buffer to bind
  17114. */
  17115. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17116. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17117. };
  17118. /** @ignore */
  17119. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17120. var _this = this;
  17121. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17122. this._activeRequests.push(request);
  17123. request.onCompleteObservable.add(function (request) {
  17124. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17125. });
  17126. return request;
  17127. };
  17128. /** @ignore */
  17129. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17130. var _this = this;
  17131. return new Promise(function (resolve, reject) {
  17132. _this._loadFile(url, function (data) {
  17133. resolve(data);
  17134. }, undefined, database, useArrayBuffer, function (request, exception) {
  17135. reject(exception);
  17136. });
  17137. });
  17138. };
  17139. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17140. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17141. var onload = function (data) {
  17142. loadedFiles[index] = data;
  17143. loadedFiles._internalCount++;
  17144. if (loadedFiles._internalCount === 6) {
  17145. onfinish(loadedFiles);
  17146. }
  17147. };
  17148. var onerror = function (request, exception) {
  17149. if (onErrorCallBack && request) {
  17150. onErrorCallBack(request.status + " " + request.statusText, exception);
  17151. }
  17152. };
  17153. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17154. };
  17155. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17156. if (onError === void 0) { onError = null; }
  17157. var loadedFiles = [];
  17158. loadedFiles._internalCount = 0;
  17159. for (var index = 0; index < 6; index++) {
  17160. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17161. }
  17162. };
  17163. // Statics
  17164. /**
  17165. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17166. * @returns true if the engine can be created
  17167. * @ignoreNaming
  17168. */
  17169. Engine.isSupported = function () {
  17170. try {
  17171. var tempcanvas = document.createElement("canvas");
  17172. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17173. return gl != null && !!window.WebGLRenderingContext;
  17174. }
  17175. catch (e) {
  17176. return false;
  17177. }
  17178. };
  17179. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17180. Engine.ExceptionList = [
  17181. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17182. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17183. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17184. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17185. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17186. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17187. ];
  17188. /** Gets the list of created engines */
  17189. Engine.Instances = new Array();
  17190. // Const statics
  17191. Engine._ALPHA_DISABLE = 0;
  17192. Engine._ALPHA_ADD = 1;
  17193. Engine._ALPHA_COMBINE = 2;
  17194. Engine._ALPHA_SUBTRACT = 3;
  17195. Engine._ALPHA_MULTIPLY = 4;
  17196. Engine._ALPHA_MAXIMIZED = 5;
  17197. Engine._ALPHA_ONEONE = 6;
  17198. Engine._ALPHA_PREMULTIPLIED = 7;
  17199. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17200. Engine._ALPHA_INTERPOLATE = 9;
  17201. Engine._ALPHA_SCREENMODE = 10;
  17202. Engine._DELAYLOADSTATE_NONE = 0;
  17203. Engine._DELAYLOADSTATE_LOADED = 1;
  17204. Engine._DELAYLOADSTATE_LOADING = 2;
  17205. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17206. Engine._TEXTUREFORMAT_ALPHA = 0;
  17207. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17208. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17209. Engine._TEXTUREFORMAT_RGB = 4;
  17210. Engine._TEXTUREFORMAT_RGBA = 5;
  17211. Engine._TEXTUREFORMAT_R32F = 6;
  17212. Engine._TEXTUREFORMAT_RG32F = 7;
  17213. Engine._TEXTUREFORMAT_RGB32F = 8;
  17214. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17215. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17216. Engine._TEXTURETYPE_FLOAT = 1;
  17217. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17218. // Depht or Stencil test Constants.
  17219. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17220. 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.
  17221. 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.
  17222. 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.
  17223. 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.
  17224. 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.
  17225. 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.
  17226. 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.
  17227. // Stencil Actions Constants.
  17228. Engine._KEEP = 0x1E00;
  17229. Engine._REPLACE = 0x1E01;
  17230. Engine._INCR = 0x1E02;
  17231. Engine._DECR = 0x1E03;
  17232. Engine._INVERT = 0x150A;
  17233. Engine._INCR_WRAP = 0x8507;
  17234. Engine._DECR_WRAP = 0x8508;
  17235. // Texture rescaling mode
  17236. Engine._SCALEMODE_FLOOR = 1;
  17237. Engine._SCALEMODE_NEAREST = 2;
  17238. Engine._SCALEMODE_CEILING = 3;
  17239. // Updatable statics so stick with vars here
  17240. /**
  17241. * Gets or sets the epsilon value used by collision engine
  17242. */
  17243. Engine.CollisionsEpsilon = 0.001;
  17244. /**
  17245. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17246. */
  17247. Engine.CodeRepository = "src/";
  17248. /**
  17249. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17250. */
  17251. Engine.ShadersRepository = "src/Shaders/";
  17252. return Engine;
  17253. }());
  17254. BABYLON.Engine = Engine;
  17255. })(BABYLON || (BABYLON = {}));
  17256. //# sourceMappingURL=babylon.engine.js.map
  17257. "use strict";
  17258. var BABYLON;
  17259. (function (BABYLON) {
  17260. /**
  17261. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17262. */
  17263. var Node = /** @class */ (function () {
  17264. /**
  17265. * Creates a new Node
  17266. * @param {string} name - the name and id to be given to this node
  17267. * @param {BABYLON.Scene} the scene this node will be added to
  17268. */
  17269. function Node(name, scene) {
  17270. if (scene === void 0) { scene = null; }
  17271. /**
  17272. * Gets or sets a string used to store user defined state for the node
  17273. */
  17274. this.state = "";
  17275. /**
  17276. * Gets or sets an object used to store user defined information for the node
  17277. */
  17278. this.metadata = null;
  17279. /**
  17280. * Gets or sets a boolean used to define if the node must be serialized
  17281. */
  17282. this.doNotSerialize = false;
  17283. /** @ignore */
  17284. this._isDisposed = false;
  17285. /**
  17286. * Gets a list of Animations associated with the node
  17287. */
  17288. this.animations = new Array();
  17289. this._ranges = {};
  17290. this._isEnabled = true;
  17291. this._isReady = true;
  17292. /** @ignore */
  17293. this._currentRenderId = -1;
  17294. this._parentRenderId = -1;
  17295. this._childRenderId = -1;
  17296. this._animationPropertiesOverride = null;
  17297. /**
  17298. * An event triggered when the mesh is disposed
  17299. */
  17300. this.onDisposeObservable = new BABYLON.Observable();
  17301. // Behaviors
  17302. this._behaviors = new Array();
  17303. this.name = name;
  17304. this.id = name;
  17305. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17306. this.uniqueId = this._scene.getUniqueId();
  17307. this._initCache();
  17308. }
  17309. /**
  17310. * Gets a boolean indicating if the node has been disposed
  17311. * @returns true if the node was disposed
  17312. */
  17313. Node.prototype.isDisposed = function () {
  17314. return this._isDisposed;
  17315. };
  17316. Object.defineProperty(Node.prototype, "parent", {
  17317. get: function () {
  17318. return this._parentNode;
  17319. },
  17320. /**
  17321. * Gets or sets the parent of the node
  17322. */
  17323. set: function (parent) {
  17324. if (this._parentNode === parent) {
  17325. return;
  17326. }
  17327. // Remove self from list of children of parent
  17328. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17329. var index = this._parentNode._children.indexOf(this);
  17330. if (index !== -1) {
  17331. this._parentNode._children.splice(index, 1);
  17332. }
  17333. }
  17334. // Store new parent
  17335. this._parentNode = parent;
  17336. // Add as child to new parent
  17337. if (this._parentNode) {
  17338. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17339. this._parentNode._children = new Array();
  17340. }
  17341. this._parentNode._children.push(this);
  17342. }
  17343. },
  17344. enumerable: true,
  17345. configurable: true
  17346. });
  17347. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17348. /**
  17349. * Gets or sets the animation properties override
  17350. */
  17351. get: function () {
  17352. return this._animationPropertiesOverride;
  17353. },
  17354. set: function (value) {
  17355. this._animationPropertiesOverride = value;
  17356. },
  17357. enumerable: true,
  17358. configurable: true
  17359. });
  17360. /**
  17361. * Gets a string idenfifying the name of the class
  17362. * @returns "Node" string
  17363. */
  17364. Node.prototype.getClassName = function () {
  17365. return "Node";
  17366. };
  17367. Object.defineProperty(Node.prototype, "onDispose", {
  17368. /**
  17369. * Sets a callback that will be raised when the node will be disposed
  17370. */
  17371. set: function (callback) {
  17372. if (this._onDisposeObserver) {
  17373. this.onDisposeObservable.remove(this._onDisposeObserver);
  17374. }
  17375. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17376. },
  17377. enumerable: true,
  17378. configurable: true
  17379. });
  17380. /**
  17381. * Gets the scene of the node
  17382. * @returns a {BABYLON.Scene}
  17383. */
  17384. Node.prototype.getScene = function () {
  17385. return this._scene;
  17386. };
  17387. /**
  17388. * Gets the engine of the node
  17389. * @returns a {BABYLON.Engine}
  17390. */
  17391. Node.prototype.getEngine = function () {
  17392. return this._scene.getEngine();
  17393. };
  17394. /**
  17395. * Attach a behavior to the node
  17396. * @see http://doc.babylonjs.com/features/behaviour
  17397. * @param behavior defines the behavior to attach
  17398. * @returns the current Node
  17399. */
  17400. Node.prototype.addBehavior = function (behavior) {
  17401. var _this = this;
  17402. var index = this._behaviors.indexOf(behavior);
  17403. if (index !== -1) {
  17404. return this;
  17405. }
  17406. behavior.init();
  17407. if (this._scene.isLoading) {
  17408. // We defer the attach when the scene will be loaded
  17409. var observer = this._scene.onDataLoadedObservable.add(function () {
  17410. behavior.attach(_this);
  17411. setTimeout(function () {
  17412. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17413. _this._scene.onDataLoadedObservable.remove(observer);
  17414. }, 0);
  17415. });
  17416. }
  17417. else {
  17418. behavior.attach(this);
  17419. }
  17420. this._behaviors.push(behavior);
  17421. return this;
  17422. };
  17423. /**
  17424. * Remove an attached behavior
  17425. * @see http://doc.babylonjs.com/features/behaviour
  17426. * @param behavior defines the behavior to attach
  17427. * @returns the current Node
  17428. */
  17429. Node.prototype.removeBehavior = function (behavior) {
  17430. var index = this._behaviors.indexOf(behavior);
  17431. if (index === -1) {
  17432. return this;
  17433. }
  17434. this._behaviors[index].detach();
  17435. this._behaviors.splice(index, 1);
  17436. return this;
  17437. };
  17438. Object.defineProperty(Node.prototype, "behaviors", {
  17439. /**
  17440. * Gets the list of attached behaviors
  17441. * @see http://doc.babylonjs.com/features/behaviour
  17442. */
  17443. get: function () {
  17444. return this._behaviors;
  17445. },
  17446. enumerable: true,
  17447. configurable: true
  17448. });
  17449. /**
  17450. * Gets an attached behavior by name
  17451. * @param name defines the name of the behavior to look for
  17452. * @see http://doc.babylonjs.com/features/behaviour
  17453. * @returns null if behavior was not found else the requested behavior
  17454. */
  17455. Node.prototype.getBehaviorByName = function (name) {
  17456. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17457. var behavior = _a[_i];
  17458. if (behavior.name === name) {
  17459. return behavior;
  17460. }
  17461. }
  17462. return null;
  17463. };
  17464. /**
  17465. * Returns the world matrix of the node
  17466. * @returns a matrix containing the node's world matrix
  17467. */
  17468. Node.prototype.getWorldMatrix = function () {
  17469. return BABYLON.Matrix.Identity();
  17470. };
  17471. // override it in derived class if you add new variables to the cache
  17472. // and call the parent class method
  17473. /** @ignore */
  17474. Node.prototype._initCache = function () {
  17475. this._cache = {};
  17476. this._cache.parent = undefined;
  17477. };
  17478. /** @ignore */
  17479. Node.prototype.updateCache = function (force) {
  17480. if (!force && this.isSynchronized())
  17481. return;
  17482. this._cache.parent = this.parent;
  17483. this._updateCache();
  17484. };
  17485. // override it in derived class if you add new variables to the cache
  17486. // and call the parent class method if !ignoreParentClass
  17487. /** @ignore */
  17488. Node.prototype._updateCache = function (ignoreParentClass) {
  17489. };
  17490. // override it in derived class if you add new variables to the cache
  17491. /** @ignore */
  17492. Node.prototype._isSynchronized = function () {
  17493. return true;
  17494. };
  17495. /** @ignore */
  17496. Node.prototype._markSyncedWithParent = function () {
  17497. if (this.parent) {
  17498. this._parentRenderId = this.parent._childRenderId;
  17499. }
  17500. };
  17501. /** @ignore */
  17502. Node.prototype.isSynchronizedWithParent = function () {
  17503. if (!this.parent) {
  17504. return true;
  17505. }
  17506. if (this._parentRenderId !== this.parent._childRenderId) {
  17507. return false;
  17508. }
  17509. return this.parent.isSynchronized();
  17510. };
  17511. /** @ignore */
  17512. Node.prototype.isSynchronized = function (updateCache) {
  17513. var check = this.hasNewParent();
  17514. check = check || !this.isSynchronizedWithParent();
  17515. check = check || !this._isSynchronized();
  17516. if (updateCache)
  17517. this.updateCache(true);
  17518. return !check;
  17519. };
  17520. /** @ignore */
  17521. Node.prototype.hasNewParent = function (update) {
  17522. if (this._cache.parent === this.parent)
  17523. return false;
  17524. if (update)
  17525. this._cache.parent = this.parent;
  17526. return true;
  17527. };
  17528. /**
  17529. * Is this node ready to be used/rendered
  17530. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17531. * @return true if the node is ready
  17532. */
  17533. Node.prototype.isReady = function (completeCheck) {
  17534. if (completeCheck === void 0) { completeCheck = false; }
  17535. return this._isReady;
  17536. };
  17537. /**
  17538. * Is this node enabled?
  17539. * 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
  17540. * @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
  17541. * @return whether this node (and its parent) is enabled
  17542. */
  17543. Node.prototype.isEnabled = function (checkAncestors) {
  17544. if (checkAncestors === void 0) { checkAncestors = true; }
  17545. if (checkAncestors === false) {
  17546. return this._isEnabled;
  17547. }
  17548. if (this._isEnabled === false) {
  17549. return false;
  17550. }
  17551. if (this.parent !== undefined && this.parent !== null) {
  17552. return this.parent.isEnabled(checkAncestors);
  17553. }
  17554. return true;
  17555. };
  17556. /**
  17557. * Set the enabled state of this node
  17558. * @param value defines the new enabled state
  17559. */
  17560. Node.prototype.setEnabled = function (value) {
  17561. this._isEnabled = value;
  17562. };
  17563. /**
  17564. * Is this node a descendant of the given node?
  17565. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17566. * @param ancestor defines the parent node to inspect
  17567. * @returns a boolean indicating if this node is a descendant of the given node
  17568. */
  17569. Node.prototype.isDescendantOf = function (ancestor) {
  17570. if (this.parent) {
  17571. if (this.parent === ancestor) {
  17572. return true;
  17573. }
  17574. return this.parent.isDescendantOf(ancestor);
  17575. }
  17576. return false;
  17577. };
  17578. /** @ignore */
  17579. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17580. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17581. if (!this._children) {
  17582. return;
  17583. }
  17584. for (var index = 0; index < this._children.length; index++) {
  17585. var item = this._children[index];
  17586. if (!predicate || predicate(item)) {
  17587. results.push(item);
  17588. }
  17589. if (!directDescendantsOnly) {
  17590. item._getDescendants(results, false, predicate);
  17591. }
  17592. }
  17593. };
  17594. /**
  17595. * Will return all nodes that have this node as ascendant
  17596. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  17597. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  17598. * @return all children nodes of all types
  17599. */
  17600. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17601. var results = new Array();
  17602. this._getDescendants(results, directDescendantsOnly, predicate);
  17603. return results;
  17604. };
  17605. /**
  17606. * Get all child-meshes of this node
  17607. * @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
  17608. * @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
  17609. * @returns an array of {BABYLON.AbstractMesh}
  17610. */
  17611. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17612. var results = [];
  17613. this._getDescendants(results, directDescendantsOnly, function (node) {
  17614. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17615. });
  17616. return results;
  17617. };
  17618. /**
  17619. * Get all child-transformNodes of this node
  17620. * @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
  17621. * @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
  17622. * @returns an array of {BABYLON.TransformNode}
  17623. */
  17624. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17625. var results = [];
  17626. this._getDescendants(results, directDescendantsOnly, function (node) {
  17627. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17628. });
  17629. return results;
  17630. };
  17631. /**
  17632. * Get all direct children of this node
  17633. * @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
  17634. * @returns an array of {BABYLON.Node}
  17635. */
  17636. Node.prototype.getChildren = function (predicate) {
  17637. return this.getDescendants(true, predicate);
  17638. };
  17639. /** @ignore */
  17640. Node.prototype._setReady = function (state) {
  17641. if (state === this._isReady) {
  17642. return;
  17643. }
  17644. if (!state) {
  17645. this._isReady = false;
  17646. return;
  17647. }
  17648. if (this.onReady) {
  17649. this.onReady(this);
  17650. }
  17651. this._isReady = true;
  17652. };
  17653. /**
  17654. * Get an animation by name
  17655. * @param name defines the name of the animation to look for
  17656. * @returns null if not found else the requested animation
  17657. */
  17658. Node.prototype.getAnimationByName = function (name) {
  17659. for (var i = 0; i < this.animations.length; i++) {
  17660. var animation = this.animations[i];
  17661. if (animation.name === name) {
  17662. return animation;
  17663. }
  17664. }
  17665. return null;
  17666. };
  17667. /**
  17668. * Creates an animation range for this node
  17669. * @param name defines the name of the range
  17670. * @param from defines the starting key
  17671. * @param to defines the end key
  17672. */
  17673. Node.prototype.createAnimationRange = function (name, from, to) {
  17674. // check name not already in use
  17675. if (!this._ranges[name]) {
  17676. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17677. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17678. if (this.animations[i]) {
  17679. this.animations[i].createRange(name, from, to);
  17680. }
  17681. }
  17682. }
  17683. };
  17684. /**
  17685. * Delete a specific animation range
  17686. * @param name defines the name of the range to delete
  17687. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17688. */
  17689. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17690. if (deleteFrames === void 0) { deleteFrames = true; }
  17691. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17692. if (this.animations[i]) {
  17693. this.animations[i].deleteRange(name, deleteFrames);
  17694. }
  17695. }
  17696. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17697. };
  17698. /**
  17699. * Get an animation range by name
  17700. * @param name defines the name of the animation range to look for
  17701. * @returns null if not found else the requested animation range
  17702. */
  17703. Node.prototype.getAnimationRange = function (name) {
  17704. return this._ranges[name];
  17705. };
  17706. /**
  17707. * Will start the animation sequence
  17708. * @param name defines the range frames for animation sequence
  17709. * @param loop defines if the animation should loop (false by default)
  17710. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17711. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17712. * @returns the object created for this animation. If range does not exist, it will return null
  17713. */
  17714. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17715. var range = this.getAnimationRange(name);
  17716. if (!range) {
  17717. return null;
  17718. }
  17719. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17720. };
  17721. /**
  17722. * Serialize animation ranges into a JSON compatible object
  17723. * @returns serialization object
  17724. */
  17725. Node.prototype.serializeAnimationRanges = function () {
  17726. var serializationRanges = [];
  17727. for (var name in this._ranges) {
  17728. var localRange = this._ranges[name];
  17729. if (!localRange) {
  17730. continue;
  17731. }
  17732. var range = {};
  17733. range.name = name;
  17734. range.from = localRange.from;
  17735. range.to = localRange.to;
  17736. serializationRanges.push(range);
  17737. }
  17738. return serializationRanges;
  17739. };
  17740. /**
  17741. * Computes the world matrix of the node
  17742. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17743. * @returns the world matrix
  17744. */
  17745. Node.prototype.computeWorldMatrix = function (force) {
  17746. return BABYLON.Matrix.Identity();
  17747. };
  17748. /**
  17749. * Releases resources associated with this node.
  17750. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17751. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17752. */
  17753. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17754. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17755. if (!doNotRecurse) {
  17756. var nodes = this.getDescendants(true);
  17757. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17758. var node = nodes_1[_i];
  17759. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17760. }
  17761. }
  17762. else {
  17763. var transformNodes = this.getChildTransformNodes(true);
  17764. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17765. var transformNode = transformNodes_1[_a];
  17766. transformNode.parent = null;
  17767. transformNode.computeWorldMatrix(true);
  17768. }
  17769. }
  17770. this.parent = null;
  17771. // Callback
  17772. this.onDisposeObservable.notifyObservers(this);
  17773. this.onDisposeObservable.clear();
  17774. // Behaviors
  17775. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17776. var behavior = _c[_b];
  17777. behavior.detach();
  17778. }
  17779. this._behaviors = [];
  17780. this._isDisposed = true;
  17781. };
  17782. /**
  17783. * Parse animation range data from a serialization object and store them into a given node
  17784. * @param node defines where to store the animation ranges
  17785. * @param parsedNode defines the serialization object to read data from
  17786. * @param scene defines the hosting scene
  17787. */
  17788. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17789. if (parsedNode.ranges) {
  17790. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17791. var data = parsedNode.ranges[index];
  17792. node.createAnimationRange(data.name, data.from, data.to);
  17793. }
  17794. }
  17795. };
  17796. __decorate([
  17797. BABYLON.serialize()
  17798. ], Node.prototype, "name", void 0);
  17799. __decorate([
  17800. BABYLON.serialize()
  17801. ], Node.prototype, "id", void 0);
  17802. __decorate([
  17803. BABYLON.serialize()
  17804. ], Node.prototype, "uniqueId", void 0);
  17805. __decorate([
  17806. BABYLON.serialize()
  17807. ], Node.prototype, "state", void 0);
  17808. __decorate([
  17809. BABYLON.serialize()
  17810. ], Node.prototype, "metadata", void 0);
  17811. return Node;
  17812. }());
  17813. BABYLON.Node = Node;
  17814. })(BABYLON || (BABYLON = {}));
  17815. //# sourceMappingURL=babylon.node.js.map
  17816. "use strict";
  17817. var BABYLON;
  17818. (function (BABYLON) {
  17819. var BoundingSphere = /** @class */ (function () {
  17820. function BoundingSphere(minimum, maximum) {
  17821. this.minimum = minimum;
  17822. this.maximum = maximum;
  17823. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17824. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17825. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17826. this.radius = distance * 0.5;
  17827. this.centerWorld = BABYLON.Vector3.Zero();
  17828. this._update(BABYLON.Matrix.Identity());
  17829. }
  17830. // Methods
  17831. BoundingSphere.prototype._update = function (world) {
  17832. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17833. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17834. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17835. };
  17836. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17837. for (var i = 0; i < 6; i++) {
  17838. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17839. return false;
  17840. }
  17841. return true;
  17842. };
  17843. BoundingSphere.prototype.intersectsPoint = function (point) {
  17844. var x = this.centerWorld.x - point.x;
  17845. var y = this.centerWorld.y - point.y;
  17846. var z = this.centerWorld.z - point.z;
  17847. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17848. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17849. return false;
  17850. return true;
  17851. };
  17852. // Statics
  17853. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17854. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17855. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17856. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17857. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17858. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17859. return false;
  17860. return true;
  17861. };
  17862. return BoundingSphere;
  17863. }());
  17864. BABYLON.BoundingSphere = BoundingSphere;
  17865. })(BABYLON || (BABYLON = {}));
  17866. //# sourceMappingURL=babylon.boundingSphere.js.map
  17867. "use strict";
  17868. var BABYLON;
  17869. (function (BABYLON) {
  17870. var BoundingBox = /** @class */ (function () {
  17871. function BoundingBox(minimum, maximum) {
  17872. this.minimum = minimum;
  17873. this.maximum = maximum;
  17874. this.vectors = new Array();
  17875. this.vectorsWorld = new Array();
  17876. // Bounding vectors
  17877. this.vectors.push(this.minimum.clone());
  17878. this.vectors.push(this.maximum.clone());
  17879. this.vectors.push(this.minimum.clone());
  17880. this.vectors[2].x = this.maximum.x;
  17881. this.vectors.push(this.minimum.clone());
  17882. this.vectors[3].y = this.maximum.y;
  17883. this.vectors.push(this.minimum.clone());
  17884. this.vectors[4].z = this.maximum.z;
  17885. this.vectors.push(this.maximum.clone());
  17886. this.vectors[5].z = this.minimum.z;
  17887. this.vectors.push(this.maximum.clone());
  17888. this.vectors[6].x = this.minimum.x;
  17889. this.vectors.push(this.maximum.clone());
  17890. this.vectors[7].y = this.minimum.y;
  17891. // OBB
  17892. this.center = this.maximum.add(this.minimum).scale(0.5);
  17893. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17894. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17895. // World
  17896. for (var index = 0; index < this.vectors.length; index++) {
  17897. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17898. }
  17899. this.minimumWorld = BABYLON.Vector3.Zero();
  17900. this.maximumWorld = BABYLON.Vector3.Zero();
  17901. this.centerWorld = BABYLON.Vector3.Zero();
  17902. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17903. this._update(BABYLON.Matrix.Identity());
  17904. }
  17905. // Methods
  17906. BoundingBox.prototype.getWorldMatrix = function () {
  17907. return this._worldMatrix;
  17908. };
  17909. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17910. this._worldMatrix.copyFrom(matrix);
  17911. return this;
  17912. };
  17913. BoundingBox.prototype._update = function (world) {
  17914. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17915. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17916. for (var index = 0; index < this.vectors.length; index++) {
  17917. var v = this.vectorsWorld[index];
  17918. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17919. if (v.x < this.minimumWorld.x)
  17920. this.minimumWorld.x = v.x;
  17921. if (v.y < this.minimumWorld.y)
  17922. this.minimumWorld.y = v.y;
  17923. if (v.z < this.minimumWorld.z)
  17924. this.minimumWorld.z = v.z;
  17925. if (v.x > this.maximumWorld.x)
  17926. this.maximumWorld.x = v.x;
  17927. if (v.y > this.maximumWorld.y)
  17928. this.maximumWorld.y = v.y;
  17929. if (v.z > this.maximumWorld.z)
  17930. this.maximumWorld.z = v.z;
  17931. }
  17932. // Extend
  17933. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17934. this.extendSizeWorld.scaleInPlace(0.5);
  17935. // OBB
  17936. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17937. this.centerWorld.scaleInPlace(0.5);
  17938. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17939. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17940. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17941. this._worldMatrix = world;
  17942. };
  17943. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17944. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17945. };
  17946. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17947. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17948. };
  17949. BoundingBox.prototype.intersectsPoint = function (point) {
  17950. var delta = -BABYLON.Epsilon;
  17951. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17952. return false;
  17953. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17954. return false;
  17955. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17956. return false;
  17957. return true;
  17958. };
  17959. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17960. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17961. };
  17962. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17963. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17964. return false;
  17965. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17966. return false;
  17967. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17968. return false;
  17969. return true;
  17970. };
  17971. // Statics
  17972. BoundingBox.Intersects = function (box0, box1) {
  17973. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17974. return false;
  17975. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17976. return false;
  17977. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17978. return false;
  17979. return true;
  17980. };
  17981. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17982. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17983. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17984. return (num <= (sphereRadius * sphereRadius));
  17985. };
  17986. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17987. for (var p = 0; p < 6; p++) {
  17988. for (var i = 0; i < 8; i++) {
  17989. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17990. return false;
  17991. }
  17992. }
  17993. }
  17994. return true;
  17995. };
  17996. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17997. for (var p = 0; p < 6; p++) {
  17998. var inCount = 8;
  17999. for (var i = 0; i < 8; i++) {
  18000. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18001. --inCount;
  18002. }
  18003. else {
  18004. break;
  18005. }
  18006. }
  18007. if (inCount === 0)
  18008. return false;
  18009. }
  18010. return true;
  18011. };
  18012. return BoundingBox;
  18013. }());
  18014. BABYLON.BoundingBox = BoundingBox;
  18015. })(BABYLON || (BABYLON = {}));
  18016. //# sourceMappingURL=babylon.boundingBox.js.map
  18017. "use strict";
  18018. var BABYLON;
  18019. (function (BABYLON) {
  18020. var computeBoxExtents = function (axis, box) {
  18021. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18022. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18023. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18024. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18025. var r = r0 + r1 + r2;
  18026. return {
  18027. min: p - r,
  18028. max: p + r
  18029. };
  18030. };
  18031. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18032. var axisOverlap = function (axis, box0, box1) {
  18033. var result0 = computeBoxExtents(axis, box0);
  18034. var result1 = computeBoxExtents(axis, box1);
  18035. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18036. };
  18037. var BoundingInfo = /** @class */ (function () {
  18038. function BoundingInfo(minimum, maximum) {
  18039. this.minimum = minimum;
  18040. this.maximum = maximum;
  18041. this._isLocked = false;
  18042. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18043. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18044. }
  18045. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18046. get: function () {
  18047. return this._isLocked;
  18048. },
  18049. set: function (value) {
  18050. this._isLocked = value;
  18051. },
  18052. enumerable: true,
  18053. configurable: true
  18054. });
  18055. // Methods
  18056. BoundingInfo.prototype.update = function (world) {
  18057. if (this._isLocked) {
  18058. return;
  18059. }
  18060. this.boundingBox._update(world);
  18061. this.boundingSphere._update(world);
  18062. };
  18063. /**
  18064. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18065. * @param center New center of the bounding info
  18066. * @param extend New extend of the bounding info
  18067. */
  18068. BoundingInfo.prototype.centerOn = function (center, extend) {
  18069. this.minimum = center.subtract(extend);
  18070. this.maximum = center.add(extend);
  18071. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18072. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18073. return this;
  18074. };
  18075. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18076. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18077. return false;
  18078. return this.boundingBox.isInFrustum(frustumPlanes);
  18079. };
  18080. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18081. /**
  18082. * Gets the world distance between the min and max points of the bounding box
  18083. */
  18084. get: function () {
  18085. var boundingBox = this.boundingBox;
  18086. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18087. return size.length();
  18088. },
  18089. enumerable: true,
  18090. configurable: true
  18091. });
  18092. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18093. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18094. };
  18095. BoundingInfo.prototype._checkCollision = function (collider) {
  18096. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18097. };
  18098. BoundingInfo.prototype.intersectsPoint = function (point) {
  18099. if (!this.boundingSphere.centerWorld) {
  18100. return false;
  18101. }
  18102. if (!this.boundingSphere.intersectsPoint(point)) {
  18103. return false;
  18104. }
  18105. if (!this.boundingBox.intersectsPoint(point)) {
  18106. return false;
  18107. }
  18108. return true;
  18109. };
  18110. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18111. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18112. return false;
  18113. }
  18114. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18115. return false;
  18116. }
  18117. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18118. return false;
  18119. }
  18120. if (!precise) {
  18121. return true;
  18122. }
  18123. var box0 = this.boundingBox;
  18124. var box1 = boundingInfo.boundingBox;
  18125. if (!axisOverlap(box0.directions[0], box0, box1))
  18126. return false;
  18127. if (!axisOverlap(box0.directions[1], box0, box1))
  18128. return false;
  18129. if (!axisOverlap(box0.directions[2], box0, box1))
  18130. return false;
  18131. if (!axisOverlap(box1.directions[0], box0, box1))
  18132. return false;
  18133. if (!axisOverlap(box1.directions[1], box0, box1))
  18134. return false;
  18135. if (!axisOverlap(box1.directions[2], box0, box1))
  18136. return false;
  18137. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18138. return false;
  18139. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18140. return false;
  18141. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18142. return false;
  18143. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18144. return false;
  18145. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18146. return false;
  18147. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18148. return false;
  18149. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18150. return false;
  18151. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18152. return false;
  18153. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18154. return false;
  18155. return true;
  18156. };
  18157. return BoundingInfo;
  18158. }());
  18159. BABYLON.BoundingInfo = BoundingInfo;
  18160. })(BABYLON || (BABYLON = {}));
  18161. //# sourceMappingURL=babylon.boundingInfo.js.map
  18162. "use strict";
  18163. var BABYLON;
  18164. (function (BABYLON) {
  18165. var TransformNode = /** @class */ (function (_super) {
  18166. __extends(TransformNode, _super);
  18167. function TransformNode(name, scene, isPure) {
  18168. if (scene === void 0) { scene = null; }
  18169. if (isPure === void 0) { isPure = true; }
  18170. var _this = _super.call(this, name, scene) || this;
  18171. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18172. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18173. _this._up = new BABYLON.Vector3(0, 1, 0);
  18174. _this._right = new BABYLON.Vector3(1, 0, 0);
  18175. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18176. // Properties
  18177. _this._rotation = BABYLON.Vector3.Zero();
  18178. _this._scaling = BABYLON.Vector3.One();
  18179. _this._isDirty = false;
  18180. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18181. _this.scalingDeterminant = 1;
  18182. _this.infiniteDistance = false;
  18183. _this.position = BABYLON.Vector3.Zero();
  18184. _this._localWorld = BABYLON.Matrix.Zero();
  18185. _this._worldMatrix = BABYLON.Matrix.Zero();
  18186. _this._worldMatrixDeterminant = 0;
  18187. _this._absolutePosition = BABYLON.Vector3.Zero();
  18188. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18189. _this._postMultiplyPivotMatrix = false;
  18190. _this._isWorldMatrixFrozen = false;
  18191. /**
  18192. * An event triggered after the world matrix is updated
  18193. */
  18194. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18195. _this._nonUniformScaling = false;
  18196. if (isPure) {
  18197. _this.getScene().addTransformNode(_this);
  18198. }
  18199. return _this;
  18200. }
  18201. /**
  18202. * Gets a string idenfifying the name of the class
  18203. * @returns "TransformNode" string
  18204. */
  18205. TransformNode.prototype.getClassName = function () {
  18206. return "TransformNode";
  18207. };
  18208. Object.defineProperty(TransformNode.prototype, "rotation", {
  18209. /**
  18210. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18211. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18212. * Default : (0.0, 0.0, 0.0)
  18213. */
  18214. get: function () {
  18215. return this._rotation;
  18216. },
  18217. set: function (newRotation) {
  18218. this._rotation = newRotation;
  18219. },
  18220. enumerable: true,
  18221. configurable: true
  18222. });
  18223. Object.defineProperty(TransformNode.prototype, "scaling", {
  18224. /**
  18225. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18226. * Default : (1.0, 1.0, 1.0)
  18227. */
  18228. get: function () {
  18229. return this._scaling;
  18230. },
  18231. /**
  18232. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18233. * Default : (1.0, 1.0, 1.0)
  18234. */
  18235. set: function (newScaling) {
  18236. this._scaling = newScaling;
  18237. },
  18238. enumerable: true,
  18239. configurable: true
  18240. });
  18241. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18242. /**
  18243. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18244. * It's null by default.
  18245. * 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)
  18246. */
  18247. get: function () {
  18248. return this._rotationQuaternion;
  18249. },
  18250. set: function (quaternion) {
  18251. this._rotationQuaternion = quaternion;
  18252. //reset the rotation vector.
  18253. if (quaternion && this.rotation.length()) {
  18254. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18255. }
  18256. },
  18257. enumerable: true,
  18258. configurable: true
  18259. });
  18260. Object.defineProperty(TransformNode.prototype, "forward", {
  18261. /**
  18262. * The forward direction of that transform in world space.
  18263. */
  18264. get: function () {
  18265. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18266. },
  18267. enumerable: true,
  18268. configurable: true
  18269. });
  18270. Object.defineProperty(TransformNode.prototype, "up", {
  18271. /**
  18272. * The up direction of that transform in world space.
  18273. */
  18274. get: function () {
  18275. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18276. },
  18277. enumerable: true,
  18278. configurable: true
  18279. });
  18280. Object.defineProperty(TransformNode.prototype, "right", {
  18281. /**
  18282. * The right direction of that transform in world space.
  18283. */
  18284. get: function () {
  18285. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18286. },
  18287. enumerable: true,
  18288. configurable: true
  18289. });
  18290. /**
  18291. * Returns the latest update of the World matrix
  18292. * Returns a Matrix.
  18293. */
  18294. TransformNode.prototype.getWorldMatrix = function () {
  18295. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18296. this.computeWorldMatrix();
  18297. }
  18298. return this._worldMatrix;
  18299. };
  18300. /**
  18301. * Returns the latest update of the World matrix determinant.
  18302. */
  18303. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18304. return this._worldMatrixDeterminant;
  18305. };
  18306. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18307. /**
  18308. * Returns directly the latest state of the mesh World matrix.
  18309. * A Matrix is returned.
  18310. */
  18311. get: function () {
  18312. return this._worldMatrix;
  18313. },
  18314. enumerable: true,
  18315. configurable: true
  18316. });
  18317. /**
  18318. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18319. * Returns the TransformNode.
  18320. */
  18321. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18322. this._poseMatrix.copyFrom(matrix);
  18323. return this;
  18324. };
  18325. /**
  18326. * Returns the mesh Pose matrix.
  18327. * Returned object : Matrix
  18328. */
  18329. TransformNode.prototype.getPoseMatrix = function () {
  18330. return this._poseMatrix;
  18331. };
  18332. TransformNode.prototype._isSynchronized = function () {
  18333. if (this._isDirty) {
  18334. return false;
  18335. }
  18336. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18337. return false;
  18338. if (this._cache.pivotMatrixUpdated) {
  18339. return false;
  18340. }
  18341. if (this.infiniteDistance) {
  18342. return false;
  18343. }
  18344. if (!this._cache.position.equals(this.position))
  18345. return false;
  18346. if (this.rotationQuaternion) {
  18347. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18348. return false;
  18349. }
  18350. if (!this._cache.rotation.equals(this.rotation))
  18351. return false;
  18352. if (!this._cache.scaling.equals(this.scaling))
  18353. return false;
  18354. return true;
  18355. };
  18356. TransformNode.prototype._initCache = function () {
  18357. _super.prototype._initCache.call(this);
  18358. this._cache.localMatrixUpdated = false;
  18359. this._cache.position = BABYLON.Vector3.Zero();
  18360. this._cache.scaling = BABYLON.Vector3.Zero();
  18361. this._cache.rotation = BABYLON.Vector3.Zero();
  18362. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18363. this._cache.billboardMode = -1;
  18364. };
  18365. TransformNode.prototype.markAsDirty = function (property) {
  18366. if (property === "rotation") {
  18367. this.rotationQuaternion = null;
  18368. }
  18369. this._currentRenderId = Number.MAX_VALUE;
  18370. this._isDirty = true;
  18371. return this;
  18372. };
  18373. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18374. /**
  18375. * Returns the current mesh absolute position.
  18376. * Retuns a Vector3.
  18377. */
  18378. get: function () {
  18379. return this._absolutePosition;
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. /**
  18385. * Sets a new matrix to apply before all other transformation
  18386. * @param matrix defines the transform matrix
  18387. * @returns the current TransformNode
  18388. */
  18389. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18390. return this.setPivotMatrix(matrix, false);
  18391. };
  18392. /**
  18393. * Sets a new pivot matrix to the current node
  18394. * @param matrix defines the new pivot matrix to use
  18395. * @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
  18396. * @returns the current TransformNode
  18397. */
  18398. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18399. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18400. this._pivotMatrix = matrix.clone();
  18401. this._cache.pivotMatrixUpdated = true;
  18402. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18403. if (this._postMultiplyPivotMatrix) {
  18404. if (!this._pivotMatrixInverse) {
  18405. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18406. }
  18407. else {
  18408. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18409. }
  18410. }
  18411. return this;
  18412. };
  18413. /**
  18414. * Returns the mesh pivot matrix.
  18415. * Default : Identity.
  18416. * A Matrix is returned.
  18417. */
  18418. TransformNode.prototype.getPivotMatrix = function () {
  18419. return this._pivotMatrix;
  18420. };
  18421. /**
  18422. * Prevents the World matrix to be computed any longer.
  18423. * Returns the TransformNode.
  18424. */
  18425. TransformNode.prototype.freezeWorldMatrix = function () {
  18426. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18427. this.computeWorldMatrix(true);
  18428. this._isWorldMatrixFrozen = true;
  18429. return this;
  18430. };
  18431. /**
  18432. * Allows back the World matrix computation.
  18433. * Returns the TransformNode.
  18434. */
  18435. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18436. this._isWorldMatrixFrozen = false;
  18437. this.computeWorldMatrix(true);
  18438. return this;
  18439. };
  18440. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18441. /**
  18442. * True if the World matrix has been frozen.
  18443. * Returns a boolean.
  18444. */
  18445. get: function () {
  18446. return this._isWorldMatrixFrozen;
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. /**
  18452. * Retuns the mesh absolute position in the World.
  18453. * Returns a Vector3.
  18454. */
  18455. TransformNode.prototype.getAbsolutePosition = function () {
  18456. this.computeWorldMatrix();
  18457. return this._absolutePosition;
  18458. };
  18459. /**
  18460. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18461. * Returns the TransformNode.
  18462. */
  18463. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18464. if (!absolutePosition) {
  18465. return this;
  18466. }
  18467. var absolutePositionX;
  18468. var absolutePositionY;
  18469. var absolutePositionZ;
  18470. if (absolutePosition.x === undefined) {
  18471. if (arguments.length < 3) {
  18472. return this;
  18473. }
  18474. absolutePositionX = arguments[0];
  18475. absolutePositionY = arguments[1];
  18476. absolutePositionZ = arguments[2];
  18477. }
  18478. else {
  18479. absolutePositionX = absolutePosition.x;
  18480. absolutePositionY = absolutePosition.y;
  18481. absolutePositionZ = absolutePosition.z;
  18482. }
  18483. if (this.parent) {
  18484. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18485. invertParentWorldMatrix.invert();
  18486. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18487. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18488. }
  18489. else {
  18490. this.position.x = absolutePositionX;
  18491. this.position.y = absolutePositionY;
  18492. this.position.z = absolutePositionZ;
  18493. }
  18494. return this;
  18495. };
  18496. /**
  18497. * Sets the mesh position in its local space.
  18498. * Returns the TransformNode.
  18499. */
  18500. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18501. this.computeWorldMatrix();
  18502. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18503. return this;
  18504. };
  18505. /**
  18506. * Returns the mesh position in the local space from the current World matrix values.
  18507. * Returns a new Vector3.
  18508. */
  18509. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18510. this.computeWorldMatrix();
  18511. var invLocalWorldMatrix = this._localWorld.clone();
  18512. invLocalWorldMatrix.invert();
  18513. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18514. };
  18515. /**
  18516. * Translates the mesh along the passed Vector3 in its local space.
  18517. * Returns the TransformNode.
  18518. */
  18519. TransformNode.prototype.locallyTranslate = function (vector3) {
  18520. this.computeWorldMatrix(true);
  18521. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18522. return this;
  18523. };
  18524. /**
  18525. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18526. * @param targetPoint the position (must be in same space as current mesh) to look at
  18527. * @param yawCor optional yaw (y-axis) correction in radians
  18528. * @param pitchCor optional pitch (x-axis) correction in radians
  18529. * @param rollCor optional roll (z-axis) correction in radians
  18530. * @param space the choosen space of the target
  18531. * @returns the TransformNode.
  18532. */
  18533. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18534. if (yawCor === void 0) { yawCor = 0; }
  18535. if (pitchCor === void 0) { pitchCor = 0; }
  18536. if (rollCor === void 0) { rollCor = 0; }
  18537. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18538. var dv = TransformNode._lookAtVectorCache;
  18539. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18540. targetPoint.subtractToRef(pos, dv);
  18541. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18542. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18543. var pitch = Math.atan2(dv.y, len);
  18544. if (this.rotationQuaternion) {
  18545. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18546. }
  18547. else {
  18548. this.rotation.x = pitch + pitchCor;
  18549. this.rotation.y = yaw + yawCor;
  18550. this.rotation.z = rollCor;
  18551. }
  18552. return this;
  18553. };
  18554. /**
  18555. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18556. * This Vector3 is expressed in the World space.
  18557. */
  18558. TransformNode.prototype.getDirection = function (localAxis) {
  18559. var result = BABYLON.Vector3.Zero();
  18560. this.getDirectionToRef(localAxis, result);
  18561. return result;
  18562. };
  18563. /**
  18564. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18565. * localAxis is expressed in the mesh local space.
  18566. * result is computed in the Wordl space from the mesh World matrix.
  18567. * Returns the TransformNode.
  18568. */
  18569. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18570. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18571. return this;
  18572. };
  18573. /**
  18574. * Sets a new pivot point to the current node
  18575. * @param point defines the new pivot point to use
  18576. * @param space defines if the point is in world or local space (local by default)
  18577. * @returns the current TransformNode
  18578. */
  18579. TransformNode.prototype.setPivotPoint = function (point, space) {
  18580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18581. if (this.getScene().getRenderId() == 0) {
  18582. this.computeWorldMatrix(true);
  18583. }
  18584. var wm = this.getWorldMatrix();
  18585. if (space == BABYLON.Space.WORLD) {
  18586. var tmat = BABYLON.Tmp.Matrix[0];
  18587. wm.invertToRef(tmat);
  18588. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18589. }
  18590. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18591. };
  18592. /**
  18593. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18594. */
  18595. TransformNode.prototype.getPivotPoint = function () {
  18596. var point = BABYLON.Vector3.Zero();
  18597. this.getPivotPointToRef(point);
  18598. return point;
  18599. };
  18600. /**
  18601. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18602. * Returns the TransformNode.
  18603. */
  18604. TransformNode.prototype.getPivotPointToRef = function (result) {
  18605. result.x = -this._pivotMatrix.m[12];
  18606. result.y = -this._pivotMatrix.m[13];
  18607. result.z = -this._pivotMatrix.m[14];
  18608. return this;
  18609. };
  18610. /**
  18611. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18612. */
  18613. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18614. var point = BABYLON.Vector3.Zero();
  18615. this.getAbsolutePivotPointToRef(point);
  18616. return point;
  18617. };
  18618. /**
  18619. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18620. * Returns the TransformNode.
  18621. */
  18622. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18623. result.x = this._pivotMatrix.m[12];
  18624. result.y = this._pivotMatrix.m[13];
  18625. result.z = this._pivotMatrix.m[14];
  18626. this.getPivotPointToRef(result);
  18627. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18628. return this;
  18629. };
  18630. /**
  18631. * Defines the passed node as the parent of the current node.
  18632. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18633. * Returns the TransformNode.
  18634. */
  18635. TransformNode.prototype.setParent = function (node) {
  18636. if (node === null) {
  18637. var rotation = BABYLON.Tmp.Quaternion[0];
  18638. var position = BABYLON.Tmp.Vector3[0];
  18639. var scale = BABYLON.Tmp.Vector3[1];
  18640. if (this.parent && this.parent.computeWorldMatrix) {
  18641. this.parent.computeWorldMatrix(true);
  18642. }
  18643. this.computeWorldMatrix(true);
  18644. this.getWorldMatrix().decompose(scale, rotation, position);
  18645. if (this.rotationQuaternion) {
  18646. this.rotationQuaternion.copyFrom(rotation);
  18647. }
  18648. else {
  18649. rotation.toEulerAnglesToRef(this.rotation);
  18650. }
  18651. this.scaling.x = scale.x;
  18652. this.scaling.y = scale.y;
  18653. this.scaling.z = scale.z;
  18654. this.position.x = position.x;
  18655. this.position.y = position.y;
  18656. this.position.z = position.z;
  18657. }
  18658. else {
  18659. var rotation = BABYLON.Tmp.Quaternion[0];
  18660. var position = BABYLON.Tmp.Vector3[0];
  18661. var scale = BABYLON.Tmp.Vector3[1];
  18662. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18663. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18664. this.computeWorldMatrix(true);
  18665. node.computeWorldMatrix(true);
  18666. node.getWorldMatrix().invertToRef(invParentMatrix);
  18667. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18668. diffMatrix.decompose(scale, rotation, position);
  18669. if (this.rotationQuaternion) {
  18670. this.rotationQuaternion.copyFrom(rotation);
  18671. }
  18672. else {
  18673. rotation.toEulerAnglesToRef(this.rotation);
  18674. }
  18675. this.position.x = position.x;
  18676. this.position.y = position.y;
  18677. this.position.z = position.z;
  18678. this.scaling.x = scale.x;
  18679. this.scaling.y = scale.y;
  18680. this.scaling.z = scale.z;
  18681. }
  18682. this.parent = node;
  18683. return this;
  18684. };
  18685. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18686. get: function () {
  18687. return this._nonUniformScaling;
  18688. },
  18689. enumerable: true,
  18690. configurable: true
  18691. });
  18692. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18693. if (this._nonUniformScaling === value) {
  18694. return false;
  18695. }
  18696. this._nonUniformScaling = true;
  18697. return true;
  18698. };
  18699. /**
  18700. * Attach the current TransformNode to another TransformNode associated with a bone
  18701. * @param bone Bone affecting the TransformNode
  18702. * @param affectedTransformNode TransformNode associated with the bone
  18703. */
  18704. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18705. this._transformToBoneReferal = affectedTransformNode;
  18706. this.parent = bone;
  18707. if (bone.getWorldMatrix().determinant() < 0) {
  18708. this.scalingDeterminant *= -1;
  18709. }
  18710. return this;
  18711. };
  18712. TransformNode.prototype.detachFromBone = function () {
  18713. if (!this.parent) {
  18714. return this;
  18715. }
  18716. if (this.parent.getWorldMatrix().determinant() < 0) {
  18717. this.scalingDeterminant *= -1;
  18718. }
  18719. this._transformToBoneReferal = null;
  18720. this.parent = null;
  18721. return this;
  18722. };
  18723. /**
  18724. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18725. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18726. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18727. * The passed axis is also normalized.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.rotate = function (axis, amount, space) {
  18731. axis.normalize();
  18732. if (!this.rotationQuaternion) {
  18733. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18734. this.rotation = BABYLON.Vector3.Zero();
  18735. }
  18736. var rotationQuaternion;
  18737. if (!space || space === BABYLON.Space.LOCAL) {
  18738. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18739. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18740. }
  18741. else {
  18742. if (this.parent) {
  18743. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18744. invertParentWorldMatrix.invert();
  18745. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18746. }
  18747. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18748. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18749. }
  18750. return this;
  18751. };
  18752. /**
  18753. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18754. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18755. * The passed axis is also normalized.
  18756. * Returns the TransformNode.
  18757. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18758. */
  18759. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18760. axis.normalize();
  18761. if (!this.rotationQuaternion) {
  18762. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18763. this.rotation.copyFromFloats(0, 0, 0);
  18764. }
  18765. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18766. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18767. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18768. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18769. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18770. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18771. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18772. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18773. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18774. return this;
  18775. };
  18776. /**
  18777. * Translates the mesh along the axis vector for the passed distance in the given space.
  18778. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18779. * Returns the TransformNode.
  18780. */
  18781. TransformNode.prototype.translate = function (axis, distance, space) {
  18782. var displacementVector = axis.scale(distance);
  18783. if (!space || space === BABYLON.Space.LOCAL) {
  18784. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18785. this.setPositionWithLocalVector(tempV3);
  18786. }
  18787. else {
  18788. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18789. }
  18790. return this;
  18791. };
  18792. /**
  18793. * Adds a rotation step to the mesh current rotation.
  18794. * x, y, z are Euler angles expressed in radians.
  18795. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18796. * This means this rotation is made in the mesh local space only.
  18797. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18798. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18799. * ```javascript
  18800. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18801. * ```
  18802. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18803. * 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.
  18804. * Returns the TransformNode.
  18805. */
  18806. TransformNode.prototype.addRotation = function (x, y, z) {
  18807. var rotationQuaternion;
  18808. if (this.rotationQuaternion) {
  18809. rotationQuaternion = this.rotationQuaternion;
  18810. }
  18811. else {
  18812. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18813. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18814. }
  18815. var accumulation = BABYLON.Tmp.Quaternion[0];
  18816. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18817. rotationQuaternion.multiplyInPlace(accumulation);
  18818. if (!this.rotationQuaternion) {
  18819. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18820. }
  18821. return this;
  18822. };
  18823. /**
  18824. * Computes the mesh World matrix and returns it.
  18825. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18826. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18827. * If the parameter `force`is set to `true`, the actual computation is done.
  18828. * Returns the mesh World Matrix.
  18829. */
  18830. TransformNode.prototype.computeWorldMatrix = function (force) {
  18831. if (this._isWorldMatrixFrozen) {
  18832. return this._worldMatrix;
  18833. }
  18834. if (!force && this.isSynchronized(true)) {
  18835. this._currentRenderId = this.getScene().getRenderId();
  18836. return this._worldMatrix;
  18837. }
  18838. this._cache.position.copyFrom(this.position);
  18839. this._cache.scaling.copyFrom(this.scaling);
  18840. this._cache.pivotMatrixUpdated = false;
  18841. this._cache.billboardMode = this.billboardMode;
  18842. this._currentRenderId = this.getScene().getRenderId();
  18843. this._childRenderId = this.getScene().getRenderId();
  18844. this._isDirty = false;
  18845. // Scaling
  18846. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18847. // Rotation
  18848. //rotate, if quaternion is set and rotation was used
  18849. if (this.rotationQuaternion) {
  18850. var len = this.rotation.length();
  18851. if (len) {
  18852. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18853. this.rotation.copyFromFloats(0, 0, 0);
  18854. }
  18855. }
  18856. if (this.rotationQuaternion) {
  18857. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18858. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18859. }
  18860. else {
  18861. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18862. this._cache.rotation.copyFrom(this.rotation);
  18863. }
  18864. // Translation
  18865. var camera = this.getScene().activeCamera;
  18866. if (this.infiniteDistance && !this.parent && camera) {
  18867. var cameraWorldMatrix = camera.getWorldMatrix();
  18868. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18869. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18870. }
  18871. else {
  18872. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18873. }
  18874. // Composing transformations
  18875. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18876. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18877. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18878. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18879. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18880. // Need to decompose each rotation here
  18881. var currentPosition = BABYLON.Tmp.Vector3[3];
  18882. if (this.parent && this.parent.getWorldMatrix) {
  18883. if (this._transformToBoneReferal) {
  18884. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18885. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18886. }
  18887. else {
  18888. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18889. }
  18890. }
  18891. else {
  18892. currentPosition.copyFrom(this.position);
  18893. }
  18894. currentPosition.subtractInPlace(camera.globalPosition);
  18895. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18896. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18897. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18898. }
  18899. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18900. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18901. }
  18902. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18903. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18904. }
  18905. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18906. }
  18907. else {
  18908. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18909. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18910. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18911. }
  18912. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18913. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18914. }
  18915. // Local world
  18916. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18917. // Parent
  18918. if (this.parent && this.parent.getWorldMatrix) {
  18919. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18920. if (this._transformToBoneReferal) {
  18921. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18922. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18923. }
  18924. else {
  18925. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18926. }
  18927. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18928. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18929. this._worldMatrix.copyFrom(this._localWorld);
  18930. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18931. }
  18932. else {
  18933. if (this._transformToBoneReferal) {
  18934. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18935. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18936. }
  18937. else {
  18938. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18939. }
  18940. }
  18941. this._markSyncedWithParent();
  18942. }
  18943. else {
  18944. this._worldMatrix.copyFrom(this._localWorld);
  18945. }
  18946. // Post multiply inverse of pivotMatrix
  18947. if (this._postMultiplyPivotMatrix) {
  18948. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18949. }
  18950. // Normal matrix
  18951. if (this.scaling.isNonUniform) {
  18952. this._updateNonUniformScalingState(true);
  18953. }
  18954. else if (this.parent && this.parent._nonUniformScaling) {
  18955. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18956. }
  18957. else {
  18958. this._updateNonUniformScalingState(false);
  18959. }
  18960. this._afterComputeWorldMatrix();
  18961. // Absolute position
  18962. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18963. // Callbacks
  18964. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18965. if (!this._poseMatrix) {
  18966. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18967. }
  18968. // Cache the determinant
  18969. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18970. return this._worldMatrix;
  18971. };
  18972. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18973. };
  18974. /**
  18975. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18976. * @param func: callback function to add
  18977. *
  18978. * Returns the TransformNode.
  18979. */
  18980. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18981. this.onAfterWorldMatrixUpdateObservable.add(func);
  18982. return this;
  18983. };
  18984. /**
  18985. * Removes a registered callback function.
  18986. * Returns the TransformNode.
  18987. */
  18988. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18989. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18990. return this;
  18991. };
  18992. /**
  18993. * Clone the current transform node
  18994. * Returns the new transform node
  18995. * @param name Name of the new clone
  18996. * @param newParent New parent for the clone
  18997. * @param doNotCloneChildren Do not clone children hierarchy
  18998. */
  18999. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19000. var _this = this;
  19001. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19002. result.name = name;
  19003. result.id = name;
  19004. if (newParent) {
  19005. result.parent = newParent;
  19006. }
  19007. if (!doNotCloneChildren) {
  19008. // Children
  19009. var directDescendants = this.getDescendants(true);
  19010. for (var index = 0; index < directDescendants.length; index++) {
  19011. var child = directDescendants[index];
  19012. if (child.clone) {
  19013. child.clone(name + "." + child.name, result);
  19014. }
  19015. }
  19016. }
  19017. return result;
  19018. };
  19019. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19020. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19021. serializationObject.type = this.getClassName();
  19022. // Parent
  19023. if (this.parent) {
  19024. serializationObject.parentId = this.parent.id;
  19025. }
  19026. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19027. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19028. }
  19029. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19030. serializationObject.isEnabled = this.isEnabled();
  19031. // Parent
  19032. if (this.parent) {
  19033. serializationObject.parentId = this.parent.id;
  19034. }
  19035. return serializationObject;
  19036. };
  19037. // Statics
  19038. /**
  19039. * Returns a new TransformNode object parsed from the source provided.
  19040. * The parameter `parsedMesh` is the source.
  19041. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19042. */
  19043. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19044. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19045. if (BABYLON.Tags) {
  19046. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19047. }
  19048. if (parsedTransformNode.localMatrix) {
  19049. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19050. }
  19051. else if (parsedTransformNode.pivotMatrix) {
  19052. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19053. }
  19054. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19055. // Parent
  19056. if (parsedTransformNode.parentId) {
  19057. transformNode._waitingParentId = parsedTransformNode.parentId;
  19058. }
  19059. return transformNode;
  19060. };
  19061. /**
  19062. * Releases resources associated with this transform node.
  19063. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19064. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19065. */
  19066. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19067. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19068. // Animations
  19069. this.getScene().stopAnimation(this);
  19070. // Remove from scene
  19071. this.getScene().removeTransformNode(this);
  19072. this.onAfterWorldMatrixUpdateObservable.clear();
  19073. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19074. };
  19075. // Statics
  19076. TransformNode.BILLBOARDMODE_NONE = 0;
  19077. TransformNode.BILLBOARDMODE_X = 1;
  19078. TransformNode.BILLBOARDMODE_Y = 2;
  19079. TransformNode.BILLBOARDMODE_Z = 4;
  19080. TransformNode.BILLBOARDMODE_ALL = 7;
  19081. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19082. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19083. __decorate([
  19084. BABYLON.serializeAsVector3()
  19085. ], TransformNode.prototype, "_rotation", void 0);
  19086. __decorate([
  19087. BABYLON.serializeAsQuaternion()
  19088. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19089. __decorate([
  19090. BABYLON.serializeAsVector3()
  19091. ], TransformNode.prototype, "_scaling", void 0);
  19092. __decorate([
  19093. BABYLON.serialize()
  19094. ], TransformNode.prototype, "billboardMode", void 0);
  19095. __decorate([
  19096. BABYLON.serialize()
  19097. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19098. __decorate([
  19099. BABYLON.serialize()
  19100. ], TransformNode.prototype, "infiniteDistance", void 0);
  19101. __decorate([
  19102. BABYLON.serializeAsVector3()
  19103. ], TransformNode.prototype, "position", void 0);
  19104. return TransformNode;
  19105. }(BABYLON.Node));
  19106. BABYLON.TransformNode = TransformNode;
  19107. })(BABYLON || (BABYLON = {}));
  19108. //# sourceMappingURL=babylon.transformNode.js.map
  19109. "use strict";
  19110. var BABYLON;
  19111. (function (BABYLON) {
  19112. var AbstractMesh = /** @class */ (function (_super) {
  19113. __extends(AbstractMesh, _super);
  19114. // Constructor
  19115. function AbstractMesh(name, scene) {
  19116. if (scene === void 0) { scene = null; }
  19117. var _this = _super.call(this, name, scene, false) || this;
  19118. _this._facetNb = 0; // facet number
  19119. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19120. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19121. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19122. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19123. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19124. _this._subDiv = {
  19125. max: 1,
  19126. X: 1,
  19127. Y: 1,
  19128. Z: 1
  19129. };
  19130. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19131. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19132. // Events
  19133. /**
  19134. * An event triggered when this mesh collides with another one
  19135. */
  19136. _this.onCollideObservable = new BABYLON.Observable();
  19137. /**
  19138. * An event triggered when the collision's position changes
  19139. */
  19140. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19141. /**
  19142. * An event triggered when material is changed
  19143. */
  19144. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19145. // Properties
  19146. _this.definedFacingForward = true; // orientation for POV movement & rotation
  19147. /**
  19148. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19149. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19150. * or
  19151. * 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.
  19152. * for more info check WebGl documentations
  19153. */
  19154. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19155. /**
  19156. * 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:
  19157. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19158. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19159. * 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.
  19160. */
  19161. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19162. /**
  19163. * 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.
  19164. * The default value is -1 which means don't break the query and wait till the result.
  19165. */
  19166. _this.occlusionRetryCount = -1;
  19167. _this._occlusionInternalRetryCounter = 0;
  19168. _this._isOccluded = false;
  19169. _this._isOcclusionQueryInProgress = false;
  19170. _this._visibility = 1.0;
  19171. _this.alphaIndex = Number.MAX_VALUE;
  19172. _this.isVisible = true;
  19173. _this.isPickable = true;
  19174. _this.showBoundingBox = false;
  19175. _this.showSubMeshesBoundingBox = false;
  19176. _this.isBlocker = false;
  19177. _this.enablePointerMoveEvents = false;
  19178. _this.renderingGroupId = 0;
  19179. _this._receiveShadows = false;
  19180. _this.renderOutline = false;
  19181. _this.outlineColor = BABYLON.Color3.Red();
  19182. _this.outlineWidth = 0.02;
  19183. _this.renderOverlay = false;
  19184. _this.overlayColor = BABYLON.Color3.Red();
  19185. _this.overlayAlpha = 0.5;
  19186. _this._hasVertexAlpha = false;
  19187. _this._useVertexColors = true;
  19188. _this._computeBonesUsingShaders = true;
  19189. _this._numBoneInfluencers = 4;
  19190. _this._applyFog = true;
  19191. _this.useOctreeForRenderingSelection = true;
  19192. _this.useOctreeForPicking = true;
  19193. _this.useOctreeForCollisions = true;
  19194. _this._layerMask = 0x0FFFFFFF;
  19195. /**
  19196. * True if the mesh must be rendered in any case.
  19197. */
  19198. _this.alwaysSelectAsActiveMesh = false;
  19199. /**
  19200. * This scene's action manager
  19201. */
  19202. _this.actionManager = null;
  19203. // Physics
  19204. _this.physicsImpostor = null;
  19205. // Collisions
  19206. _this._checkCollisions = false;
  19207. _this._collisionMask = -1;
  19208. _this._collisionGroup = -1;
  19209. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19210. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19211. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19212. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19213. // Edges
  19214. _this.edgesWidth = 1;
  19215. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19216. // Cache
  19217. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19218. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19219. _this._renderId = 0;
  19220. _this._intersectionsInProgress = new Array();
  19221. _this._unIndexed = false;
  19222. _this._lightSources = new Array();
  19223. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19224. if (collidedMesh === void 0) { collidedMesh = null; }
  19225. //TODO move this to the collision coordinator!
  19226. if (_this.getScene().workerCollisions)
  19227. newPosition.multiplyInPlace(_this._collider._radius);
  19228. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19229. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19230. _this.position.addInPlace(_this._diffPositionForCollisions);
  19231. }
  19232. if (collidedMesh) {
  19233. _this.onCollideObservable.notifyObservers(collidedMesh);
  19234. }
  19235. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19236. };
  19237. _this.getScene().addMesh(_this);
  19238. _this._resyncLightSources();
  19239. return _this;
  19240. }
  19241. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19242. get: function () {
  19243. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19244. },
  19245. enumerable: true,
  19246. configurable: true
  19247. });
  19248. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19249. get: function () {
  19250. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19256. get: function () {
  19257. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19258. },
  19259. enumerable: true,
  19260. configurable: true
  19261. });
  19262. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19263. get: function () {
  19264. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19265. },
  19266. enumerable: true,
  19267. configurable: true
  19268. });
  19269. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19270. get: function () {
  19271. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19272. },
  19273. enumerable: true,
  19274. configurable: true
  19275. });
  19276. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19277. /**
  19278. * Read-only : the number of facets in the mesh
  19279. */
  19280. get: function () {
  19281. return this._facetNb;
  19282. },
  19283. enumerable: true,
  19284. configurable: true
  19285. });
  19286. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19287. /**
  19288. * The number (integer) of subdivisions per axis in the partioning space
  19289. */
  19290. get: function () {
  19291. return this._partitioningSubdivisions;
  19292. },
  19293. set: function (nb) {
  19294. this._partitioningSubdivisions = nb;
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19300. /**
  19301. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19302. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19303. */
  19304. get: function () {
  19305. return this._partitioningBBoxRatio;
  19306. },
  19307. set: function (ratio) {
  19308. this._partitioningBBoxRatio = ratio;
  19309. },
  19310. enumerable: true,
  19311. configurable: true
  19312. });
  19313. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19314. /**
  19315. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19316. * Works only for updatable meshes.
  19317. * Doesn't work with multi-materials.
  19318. */
  19319. get: function () {
  19320. return this._facetDepthSort;
  19321. },
  19322. set: function (sort) {
  19323. this._facetDepthSort = sort;
  19324. },
  19325. enumerable: true,
  19326. configurable: true
  19327. });
  19328. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19329. /**
  19330. * The location (Vector3) where the facet depth sort must be computed from.
  19331. * By default, the active camera position.
  19332. * Used only when facet depth sort is enabled.
  19333. */
  19334. get: function () {
  19335. return this._facetDepthSortFrom;
  19336. },
  19337. set: function (location) {
  19338. this._facetDepthSortFrom = location;
  19339. },
  19340. enumerable: true,
  19341. configurable: true
  19342. });
  19343. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19344. /**
  19345. * Read-only boolean : is the feature facetData enabled ?
  19346. */
  19347. get: function () {
  19348. return this._facetDataEnabled;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19354. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19355. return false;
  19356. }
  19357. this._markSubMeshesAsMiscDirty();
  19358. return true;
  19359. };
  19360. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19361. set: function (callback) {
  19362. if (this._onCollideObserver) {
  19363. this.onCollideObservable.remove(this._onCollideObserver);
  19364. }
  19365. this._onCollideObserver = this.onCollideObservable.add(callback);
  19366. },
  19367. enumerable: true,
  19368. configurable: true
  19369. });
  19370. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19371. set: function (callback) {
  19372. if (this._onCollisionPositionChangeObserver) {
  19373. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19374. }
  19375. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19376. },
  19377. enumerable: true,
  19378. configurable: true
  19379. });
  19380. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19381. /**
  19382. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  19383. */
  19384. get: function () {
  19385. return this._isOccluded;
  19386. },
  19387. set: function (value) {
  19388. this._isOccluded = value;
  19389. },
  19390. enumerable: true,
  19391. configurable: true
  19392. });
  19393. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19394. /**
  19395. * Flag to check the progress status of the query
  19396. */
  19397. get: function () {
  19398. return this._isOcclusionQueryInProgress;
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19404. /**
  19405. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19406. */
  19407. get: function () {
  19408. return this._visibility;
  19409. },
  19410. /**
  19411. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19412. */
  19413. set: function (value) {
  19414. if (this._visibility === value) {
  19415. return;
  19416. }
  19417. this._visibility = value;
  19418. this._markSubMeshesAsMiscDirty();
  19419. },
  19420. enumerable: true,
  19421. configurable: true
  19422. });
  19423. Object.defineProperty(AbstractMesh.prototype, "material", {
  19424. get: function () {
  19425. return this._material;
  19426. },
  19427. set: function (value) {
  19428. if (this._material === value) {
  19429. return;
  19430. }
  19431. this._material = value;
  19432. if (this.onMaterialChangedObservable.hasObservers) {
  19433. this.onMaterialChangedObservable.notifyObservers(this);
  19434. }
  19435. if (!this.subMeshes) {
  19436. return;
  19437. }
  19438. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19439. var subMesh = _a[_i];
  19440. subMesh.setEffect(null);
  19441. }
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19447. get: function () {
  19448. return this._receiveShadows;
  19449. },
  19450. set: function (value) {
  19451. if (this._receiveShadows === value) {
  19452. return;
  19453. }
  19454. this._receiveShadows = value;
  19455. this._markSubMeshesAsLightDirty();
  19456. },
  19457. enumerable: true,
  19458. configurable: true
  19459. });
  19460. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19461. get: function () {
  19462. return this._hasVertexAlpha;
  19463. },
  19464. set: function (value) {
  19465. if (this._hasVertexAlpha === value) {
  19466. return;
  19467. }
  19468. this._hasVertexAlpha = value;
  19469. this._markSubMeshesAsAttributesDirty();
  19470. this._markSubMeshesAsMiscDirty();
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19476. get: function () {
  19477. return this._useVertexColors;
  19478. },
  19479. set: function (value) {
  19480. if (this._useVertexColors === value) {
  19481. return;
  19482. }
  19483. this._useVertexColors = value;
  19484. this._markSubMeshesAsAttributesDirty();
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19490. get: function () {
  19491. return this._computeBonesUsingShaders;
  19492. },
  19493. set: function (value) {
  19494. if (this._computeBonesUsingShaders === value) {
  19495. return;
  19496. }
  19497. this._computeBonesUsingShaders = value;
  19498. this._markSubMeshesAsAttributesDirty();
  19499. },
  19500. enumerable: true,
  19501. configurable: true
  19502. });
  19503. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19504. get: function () {
  19505. return this._numBoneInfluencers;
  19506. },
  19507. set: function (value) {
  19508. if (this._numBoneInfluencers === value) {
  19509. return;
  19510. }
  19511. this._numBoneInfluencers = value;
  19512. this._markSubMeshesAsAttributesDirty();
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19518. get: function () {
  19519. return this._applyFog;
  19520. },
  19521. set: function (value) {
  19522. if (this._applyFog === value) {
  19523. return;
  19524. }
  19525. this._applyFog = value;
  19526. this._markSubMeshesAsMiscDirty();
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19532. get: function () {
  19533. return this._layerMask;
  19534. },
  19535. set: function (value) {
  19536. if (value === this._layerMask) {
  19537. return;
  19538. }
  19539. this._layerMask = value;
  19540. this._resyncLightSources();
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19546. get: function () {
  19547. return this._collisionMask;
  19548. },
  19549. set: function (mask) {
  19550. this._collisionMask = !isNaN(mask) ? mask : -1;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19556. get: function () {
  19557. return this._collisionGroup;
  19558. },
  19559. set: function (mask) {
  19560. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19566. get: function () {
  19567. return null;
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19573. get: function () {
  19574. return this._skeleton;
  19575. },
  19576. set: function (value) {
  19577. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19578. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19579. }
  19580. if (value && value.needInitialSkinMatrix) {
  19581. value._registerMeshWithPoseMatrix(this);
  19582. }
  19583. this._skeleton = value;
  19584. if (!this._skeleton) {
  19585. this._bonesTransformMatrices = null;
  19586. }
  19587. this._markSubMeshesAsAttributesDirty();
  19588. },
  19589. enumerable: true,
  19590. configurable: true
  19591. });
  19592. /**
  19593. * Returns the string "AbstractMesh"
  19594. */
  19595. AbstractMesh.prototype.getClassName = function () {
  19596. return "AbstractMesh";
  19597. };
  19598. /**
  19599. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19600. */
  19601. AbstractMesh.prototype.toString = function (fullDetails) {
  19602. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19603. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19604. if (this._skeleton) {
  19605. ret += ", skeleton: " + this._skeleton.name;
  19606. }
  19607. if (fullDetails) {
  19608. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19609. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19610. }
  19611. return ret;
  19612. };
  19613. AbstractMesh.prototype._rebuild = function () {
  19614. if (this._occlusionQuery) {
  19615. this._occlusionQuery = null;
  19616. }
  19617. if (this._edgesRenderer) {
  19618. this._edgesRenderer._rebuild();
  19619. }
  19620. if (!this.subMeshes) {
  19621. return;
  19622. }
  19623. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19624. var subMesh = _a[_i];
  19625. subMesh._rebuild();
  19626. }
  19627. };
  19628. AbstractMesh.prototype._resyncLightSources = function () {
  19629. this._lightSources.length = 0;
  19630. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19631. var light = _a[_i];
  19632. if (!light.isEnabled()) {
  19633. continue;
  19634. }
  19635. if (light.canAffectMesh(this)) {
  19636. this._lightSources.push(light);
  19637. }
  19638. }
  19639. this._markSubMeshesAsLightDirty();
  19640. };
  19641. AbstractMesh.prototype._resyncLighSource = function (light) {
  19642. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19643. var index = this._lightSources.indexOf(light);
  19644. if (index === -1) {
  19645. if (!isIn) {
  19646. return;
  19647. }
  19648. this._lightSources.push(light);
  19649. }
  19650. else {
  19651. if (isIn) {
  19652. return;
  19653. }
  19654. this._lightSources.splice(index, 1);
  19655. }
  19656. this._markSubMeshesAsLightDirty();
  19657. };
  19658. AbstractMesh.prototype._removeLightSource = function (light) {
  19659. var index = this._lightSources.indexOf(light);
  19660. if (index === -1) {
  19661. return;
  19662. }
  19663. this._lightSources.splice(index, 1);
  19664. this._markSubMeshesAsLightDirty();
  19665. };
  19666. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19667. if (!this.subMeshes) {
  19668. return;
  19669. }
  19670. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19671. var subMesh = _a[_i];
  19672. if (subMesh._materialDefines) {
  19673. func(subMesh._materialDefines);
  19674. }
  19675. }
  19676. };
  19677. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19678. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19679. };
  19680. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19681. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19682. };
  19683. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19684. if (!this.subMeshes) {
  19685. return;
  19686. }
  19687. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19688. var subMesh = _a[_i];
  19689. var material = subMesh.getMaterial();
  19690. if (material) {
  19691. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19692. }
  19693. }
  19694. };
  19695. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19696. /**
  19697. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19698. * Default : (1.0, 1.0, 1.0)
  19699. */
  19700. get: function () {
  19701. return this._scaling;
  19702. },
  19703. /**
  19704. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19705. * Default : (1.0, 1.0, 1.0)
  19706. */
  19707. set: function (newScaling) {
  19708. this._scaling = newScaling;
  19709. if (this.physicsImpostor) {
  19710. this.physicsImpostor.forceUpdate();
  19711. }
  19712. },
  19713. enumerable: true,
  19714. configurable: true
  19715. });
  19716. // Methods
  19717. /**
  19718. * Disables the mesh edger rendering mode.
  19719. * Returns the AbstractMesh.
  19720. */
  19721. AbstractMesh.prototype.disableEdgesRendering = function () {
  19722. if (this._edgesRenderer) {
  19723. this._edgesRenderer.dispose();
  19724. this._edgesRenderer = null;
  19725. }
  19726. return this;
  19727. };
  19728. /**
  19729. * Enables the edge rendering mode on the mesh.
  19730. * This mode makes the mesh edges visible.
  19731. * Returns the AbstractMesh.
  19732. */
  19733. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19734. if (epsilon === void 0) { epsilon = 0.95; }
  19735. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19736. this.disableEdgesRendering();
  19737. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19738. return this;
  19739. };
  19740. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19741. /**
  19742. * Returns true if the mesh is blocked. Used by the class Mesh.
  19743. * Returns the boolean `false` by default.
  19744. */
  19745. get: function () {
  19746. return false;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. /**
  19752. * Returns the mesh itself by default, used by the class Mesh.
  19753. * Returned type : AbstractMesh
  19754. */
  19755. AbstractMesh.prototype.getLOD = function (camera) {
  19756. return this;
  19757. };
  19758. /**
  19759. * Returns 0 by default, used by the class Mesh.
  19760. * Returns an integer.
  19761. */
  19762. AbstractMesh.prototype.getTotalVertices = function () {
  19763. return 0;
  19764. };
  19765. /**
  19766. * Returns null by default, used by the class Mesh.
  19767. * Returned type : integer array
  19768. */
  19769. AbstractMesh.prototype.getIndices = function () {
  19770. return null;
  19771. };
  19772. /**
  19773. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19774. * Returned type : float array or Float32Array
  19775. */
  19776. AbstractMesh.prototype.getVerticesData = function (kind) {
  19777. return null;
  19778. };
  19779. /**
  19780. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19781. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19782. * The `data` are either a numeric array either a Float32Array.
  19783. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19784. * 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).
  19785. * Note that a new underlying VertexBuffer object is created each call.
  19786. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19787. *
  19788. * Possible `kind` values :
  19789. * - BABYLON.VertexBuffer.PositionKind
  19790. * - BABYLON.VertexBuffer.UVKind
  19791. * - BABYLON.VertexBuffer.UV2Kind
  19792. * - BABYLON.VertexBuffer.UV3Kind
  19793. * - BABYLON.VertexBuffer.UV4Kind
  19794. * - BABYLON.VertexBuffer.UV5Kind
  19795. * - BABYLON.VertexBuffer.UV6Kind
  19796. * - BABYLON.VertexBuffer.ColorKind
  19797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19801. *
  19802. * Returns the Mesh.
  19803. */
  19804. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19805. return this;
  19806. };
  19807. /**
  19808. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19809. * If the mesh has no geometry, it is simply returned as it is.
  19810. * The `data` are either a numeric array either a Float32Array.
  19811. * No new underlying VertexBuffer object is created.
  19812. * 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.
  19813. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19814. *
  19815. * Possible `kind` values :
  19816. * - BABYLON.VertexBuffer.PositionKind
  19817. * - BABYLON.VertexBuffer.UVKind
  19818. * - BABYLON.VertexBuffer.UV2Kind
  19819. * - BABYLON.VertexBuffer.UV3Kind
  19820. * - BABYLON.VertexBuffer.UV4Kind
  19821. * - BABYLON.VertexBuffer.UV5Kind
  19822. * - BABYLON.VertexBuffer.UV6Kind
  19823. * - BABYLON.VertexBuffer.ColorKind
  19824. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19825. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19826. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19827. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19828. *
  19829. * Returns the Mesh.
  19830. */
  19831. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19832. return this;
  19833. };
  19834. /**
  19835. * Sets the mesh indices.
  19836. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19837. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19838. * This method creates a new index buffer each call.
  19839. * Returns the Mesh.
  19840. */
  19841. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19842. return this;
  19843. };
  19844. /** Returns false by default, used by the class Mesh.
  19845. * Returns a boolean
  19846. */
  19847. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19848. return false;
  19849. };
  19850. /**
  19851. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19852. * Returns a BoundingInfo
  19853. */
  19854. AbstractMesh.prototype.getBoundingInfo = function () {
  19855. if (this._masterMesh) {
  19856. return this._masterMesh.getBoundingInfo();
  19857. }
  19858. if (!this._boundingInfo) {
  19859. // this._boundingInfo is being created here
  19860. this._updateBoundingInfo();
  19861. }
  19862. // cannot be null.
  19863. return this._boundingInfo;
  19864. };
  19865. /**
  19866. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19867. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19868. */
  19869. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19870. if (includeDescendants === void 0) { includeDescendants = true; }
  19871. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19872. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19873. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19874. if (maxDimension === 0) {
  19875. return this;
  19876. }
  19877. var scale = 1 / maxDimension;
  19878. this.scaling.scaleInPlace(scale);
  19879. return this;
  19880. };
  19881. /**
  19882. * Sets a mesh new object BoundingInfo.
  19883. * Returns the AbstractMesh.
  19884. */
  19885. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19886. this._boundingInfo = boundingInfo;
  19887. return this;
  19888. };
  19889. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19890. get: function () {
  19891. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. AbstractMesh.prototype._preActivate = function () {
  19897. };
  19898. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19899. };
  19900. AbstractMesh.prototype._activate = function (renderId) {
  19901. this._renderId = renderId;
  19902. };
  19903. /**
  19904. * Returns the latest update of the World matrix
  19905. * Returns a Matrix.
  19906. */
  19907. AbstractMesh.prototype.getWorldMatrix = function () {
  19908. if (this._masterMesh) {
  19909. return this._masterMesh.getWorldMatrix();
  19910. }
  19911. return _super.prototype.getWorldMatrix.call(this);
  19912. };
  19913. /**
  19914. * Returns the latest update of the World matrix determinant.
  19915. */
  19916. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19917. if (this._masterMesh) {
  19918. return this._masterMesh._getWorldMatrixDeterminant();
  19919. }
  19920. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19921. };
  19922. // ================================== Point of View Movement =================================
  19923. /**
  19924. * Perform relative position change from the point of view of behind the front of the mesh.
  19925. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19926. * Supports definition of mesh facing forward or backward.
  19927. * @param {number} amountRight
  19928. * @param {number} amountUp
  19929. * @param {number} amountForward
  19930. *
  19931. * Returns the AbstractMesh.
  19932. */
  19933. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19934. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19935. return this;
  19936. };
  19937. /**
  19938. * Calculate relative position change from the point of view of behind the front of the mesh.
  19939. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19940. * Supports definition of mesh facing forward or backward.
  19941. * @param {number} amountRight
  19942. * @param {number} amountUp
  19943. * @param {number} amountForward
  19944. *
  19945. * Returns a new Vector3.
  19946. */
  19947. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19948. var rotMatrix = new BABYLON.Matrix();
  19949. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19950. rotQuaternion.toRotationMatrix(rotMatrix);
  19951. var translationDelta = BABYLON.Vector3.Zero();
  19952. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19953. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19954. return translationDelta;
  19955. };
  19956. // ================================== Point of View Rotation =================================
  19957. /**
  19958. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19959. * Supports definition of mesh facing forward or backward.
  19960. * @param {number} flipBack
  19961. * @param {number} twirlClockwise
  19962. * @param {number} tiltRight
  19963. *
  19964. * Returns the AbstractMesh.
  19965. */
  19966. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19967. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19968. return this;
  19969. };
  19970. /**
  19971. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19972. * Supports definition of mesh facing forward or backward.
  19973. * @param {number} flipBack
  19974. * @param {number} twirlClockwise
  19975. * @param {number} tiltRight
  19976. *
  19977. * Returns a new Vector3.
  19978. */
  19979. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19980. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19981. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19982. };
  19983. /**
  19984. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19985. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19986. */
  19987. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19988. if (includeDescendants === void 0) { includeDescendants = true; }
  19989. this.computeWorldMatrix(true);
  19990. var min;
  19991. var max;
  19992. var boundingInfo = this.getBoundingInfo();
  19993. if (!this.subMeshes) {
  19994. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19995. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19996. }
  19997. else {
  19998. min = boundingInfo.boundingBox.minimumWorld;
  19999. max = boundingInfo.boundingBox.maximumWorld;
  20000. }
  20001. if (includeDescendants) {
  20002. var descendants = this.getDescendants(false);
  20003. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20004. var descendant = descendants_1[_i];
  20005. var childMesh = descendant;
  20006. childMesh.computeWorldMatrix(true);
  20007. //make sure we have the needed params to get mix and max
  20008. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20009. continue;
  20010. }
  20011. var childBoundingInfo = childMesh.getBoundingInfo();
  20012. var boundingBox = childBoundingInfo.boundingBox;
  20013. var minBox = boundingBox.minimumWorld;
  20014. var maxBox = boundingBox.maximumWorld;
  20015. BABYLON.Tools.CheckExtends(minBox, min, max);
  20016. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20017. }
  20018. }
  20019. return {
  20020. min: min,
  20021. max: max
  20022. };
  20023. };
  20024. /**
  20025. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  20026. * Returns the AbstractMesh.
  20027. */
  20028. AbstractMesh.prototype._updateBoundingInfo = function () {
  20029. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20030. this._boundingInfo.update(this.worldMatrixFromCache);
  20031. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20032. return this;
  20033. };
  20034. /**
  20035. * Update a mesh's children BoundingInfo objects only.
  20036. * Returns the AbstractMesh.
  20037. */
  20038. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20039. if (!this.subMeshes) {
  20040. return this;
  20041. }
  20042. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20043. var subMesh = this.subMeshes[subIndex];
  20044. if (!subMesh.IsGlobal) {
  20045. subMesh.updateBoundingInfo(matrix);
  20046. }
  20047. }
  20048. return this;
  20049. };
  20050. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20051. // Bounding info
  20052. this._updateBoundingInfo();
  20053. };
  20054. /**
  20055. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20056. * A mesh is in the frustum if its bounding box intersects the frustum.
  20057. * Boolean returned.
  20058. */
  20059. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20060. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20061. };
  20062. /**
  20063. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20064. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20065. * Boolean returned.
  20066. */
  20067. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20068. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20069. ;
  20070. };
  20071. /**
  20072. * True if the mesh intersects another mesh or a SolidParticle object.
  20073. * 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)
  20074. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20075. * Returns a boolean.
  20076. */
  20077. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20078. if (precise === void 0) { precise = false; }
  20079. if (!this._boundingInfo || !mesh._boundingInfo) {
  20080. return false;
  20081. }
  20082. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20083. return true;
  20084. }
  20085. if (includeDescendants) {
  20086. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20087. var child = _a[_i];
  20088. if (child.intersectsMesh(mesh, precise, true)) {
  20089. return true;
  20090. }
  20091. }
  20092. }
  20093. return false;
  20094. };
  20095. /**
  20096. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  20097. * Returns a boolean.
  20098. */
  20099. AbstractMesh.prototype.intersectsPoint = function (point) {
  20100. if (!this._boundingInfo) {
  20101. return false;
  20102. }
  20103. return this._boundingInfo.intersectsPoint(point);
  20104. };
  20105. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20106. return this.physicsImpostor;
  20107. };
  20108. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20109. if (camera === void 0) { camera = null; }
  20110. if (!camera) {
  20111. camera = this.getScene().activeCamera;
  20112. }
  20113. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20114. };
  20115. /**
  20116. * Returns the distance from the mesh to the active camera.
  20117. * Returns a float.
  20118. */
  20119. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20120. if (camera === void 0) { camera = null; }
  20121. if (!camera) {
  20122. camera = this.getScene().activeCamera;
  20123. }
  20124. return this.absolutePosition.subtract(camera.position).length();
  20125. };
  20126. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20127. if (!this.physicsImpostor) {
  20128. return this;
  20129. }
  20130. this.physicsImpostor.applyImpulse(force, contactPoint);
  20131. return this;
  20132. };
  20133. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20134. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20135. return this;
  20136. }
  20137. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20138. mainPivot: pivot1,
  20139. connectedPivot: pivot2,
  20140. nativeParams: options
  20141. });
  20142. return this;
  20143. };
  20144. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20145. // Collisions
  20146. /**
  20147. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  20148. * Default `false`.
  20149. */
  20150. get: function () {
  20151. return this._checkCollisions;
  20152. },
  20153. set: function (collisionEnabled) {
  20154. this._checkCollisions = collisionEnabled;
  20155. if (this.getScene().workerCollisions) {
  20156. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20157. }
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20163. /**
  20164. * Gets Collider object used to compute collisions (not physics)
  20165. */
  20166. get: function () {
  20167. return this._collider;
  20168. },
  20169. enumerable: true,
  20170. configurable: true
  20171. });
  20172. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20173. var globalPosition = this.getAbsolutePosition();
  20174. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20175. if (!this._collider) {
  20176. this._collider = new BABYLON.Collider();
  20177. }
  20178. this._collider._radius = this.ellipsoid;
  20179. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20180. return this;
  20181. };
  20182. // Submeshes octree
  20183. /**
  20184. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20185. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  20186. * Returns an Octree of submeshes.
  20187. */
  20188. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20189. if (maxCapacity === void 0) { maxCapacity = 64; }
  20190. if (maxDepth === void 0) { maxDepth = 2; }
  20191. if (!this._submeshesOctree) {
  20192. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20193. }
  20194. this.computeWorldMatrix(true);
  20195. var boundingInfo = this.getBoundingInfo();
  20196. // Update octree
  20197. var bbox = boundingInfo.boundingBox;
  20198. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20199. return this._submeshesOctree;
  20200. };
  20201. // Collisions
  20202. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20203. this._generatePointsArray();
  20204. if (!this._positions) {
  20205. return this;
  20206. }
  20207. // Transformation
  20208. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20209. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20210. subMesh._lastColliderWorldVertices = [];
  20211. subMesh._trianglePlanes = [];
  20212. var start = subMesh.verticesStart;
  20213. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20214. for (var i = start; i < end; i++) {
  20215. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20216. }
  20217. }
  20218. // Collide
  20219. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20220. if (collider.collisionFound) {
  20221. collider.collidedMesh = this;
  20222. }
  20223. return this;
  20224. };
  20225. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20226. var subMeshes;
  20227. var len;
  20228. // Octrees
  20229. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20230. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20231. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20232. len = intersections.length;
  20233. subMeshes = intersections.data;
  20234. }
  20235. else {
  20236. subMeshes = this.subMeshes;
  20237. len = subMeshes.length;
  20238. }
  20239. for (var index = 0; index < len; index++) {
  20240. var subMesh = subMeshes[index];
  20241. // Bounding test
  20242. if (len > 1 && !subMesh._checkCollision(collider))
  20243. continue;
  20244. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20245. }
  20246. return this;
  20247. };
  20248. AbstractMesh.prototype._checkCollision = function (collider) {
  20249. // Bounding box test
  20250. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20251. return this;
  20252. // Transformation matrix
  20253. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20254. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20255. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20256. return this;
  20257. };
  20258. // Picking
  20259. AbstractMesh.prototype._generatePointsArray = function () {
  20260. return false;
  20261. };
  20262. /**
  20263. * Checks if the passed Ray intersects with the mesh.
  20264. * Returns an object PickingInfo.
  20265. */
  20266. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20267. var pickingInfo = new BABYLON.PickingInfo();
  20268. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20269. return pickingInfo;
  20270. }
  20271. if (!this._generatePointsArray()) {
  20272. return pickingInfo;
  20273. }
  20274. var intersectInfo = null;
  20275. // Octrees
  20276. var subMeshes;
  20277. var len;
  20278. if (this._submeshesOctree && this.useOctreeForPicking) {
  20279. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20280. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20281. len = intersections.length;
  20282. subMeshes = intersections.data;
  20283. }
  20284. else {
  20285. subMeshes = this.subMeshes;
  20286. len = subMeshes.length;
  20287. }
  20288. for (var index = 0; index < len; index++) {
  20289. var subMesh = subMeshes[index];
  20290. // Bounding test
  20291. if (len > 1 && !subMesh.canIntersects(ray))
  20292. continue;
  20293. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20294. if (currentIntersectInfo) {
  20295. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20296. intersectInfo = currentIntersectInfo;
  20297. intersectInfo.subMeshId = index;
  20298. if (fastCheck) {
  20299. break;
  20300. }
  20301. }
  20302. }
  20303. }
  20304. if (intersectInfo) {
  20305. // Get picked point
  20306. var world = this.getWorldMatrix();
  20307. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20308. var direction = ray.direction.clone();
  20309. direction = direction.scale(intersectInfo.distance);
  20310. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20311. var pickedPoint = worldOrigin.add(worldDirection);
  20312. // Return result
  20313. pickingInfo.hit = true;
  20314. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20315. pickingInfo.pickedPoint = pickedPoint;
  20316. pickingInfo.pickedMesh = this;
  20317. pickingInfo.bu = intersectInfo.bu || 0;
  20318. pickingInfo.bv = intersectInfo.bv || 0;
  20319. pickingInfo.faceId = intersectInfo.faceId;
  20320. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20321. return pickingInfo;
  20322. }
  20323. return pickingInfo;
  20324. };
  20325. /**
  20326. * Clones the mesh, used by the class Mesh.
  20327. * Just returns `null` for an AbstractMesh.
  20328. */
  20329. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20330. return null;
  20331. };
  20332. /**
  20333. * Disposes all the mesh submeshes.
  20334. * Returns the AbstractMesh.
  20335. */
  20336. AbstractMesh.prototype.releaseSubMeshes = function () {
  20337. if (this.subMeshes) {
  20338. while (this.subMeshes.length) {
  20339. this.subMeshes[0].dispose();
  20340. }
  20341. }
  20342. else {
  20343. this.subMeshes = new Array();
  20344. }
  20345. return this;
  20346. };
  20347. /**
  20348. * Releases resources associated with this abstract mesh.
  20349. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20350. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20351. */
  20352. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20353. var _this = this;
  20354. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20355. var index;
  20356. // Smart Array Retainers.
  20357. this.getScene().freeActiveMeshes();
  20358. this.getScene().freeRenderingGroups();
  20359. // Action manager
  20360. if (this.actionManager !== undefined && this.actionManager !== null) {
  20361. this.actionManager.dispose();
  20362. this.actionManager = null;
  20363. }
  20364. // Skeleton
  20365. this._skeleton = null;
  20366. // Physics
  20367. if (this.physicsImpostor) {
  20368. this.physicsImpostor.dispose();
  20369. }
  20370. // Intersections in progress
  20371. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20372. var other = this._intersectionsInProgress[index];
  20373. var pos = other._intersectionsInProgress.indexOf(this);
  20374. other._intersectionsInProgress.splice(pos, 1);
  20375. }
  20376. this._intersectionsInProgress = [];
  20377. // Lights
  20378. var lights = this.getScene().lights;
  20379. lights.forEach(function (light) {
  20380. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20381. if (meshIndex !== -1) {
  20382. light.includedOnlyMeshes.splice(meshIndex, 1);
  20383. }
  20384. meshIndex = light.excludedMeshes.indexOf(_this);
  20385. if (meshIndex !== -1) {
  20386. light.excludedMeshes.splice(meshIndex, 1);
  20387. }
  20388. // Shadow generators
  20389. var generator = light.getShadowGenerator();
  20390. if (generator) {
  20391. var shadowMap = generator.getShadowMap();
  20392. if (shadowMap && shadowMap.renderList) {
  20393. meshIndex = shadowMap.renderList.indexOf(_this);
  20394. if (meshIndex !== -1) {
  20395. shadowMap.renderList.splice(meshIndex, 1);
  20396. }
  20397. }
  20398. }
  20399. });
  20400. // Edges
  20401. if (this._edgesRenderer) {
  20402. this._edgesRenderer.dispose();
  20403. this._edgesRenderer = null;
  20404. }
  20405. // SubMeshes
  20406. if (this.getClassName() !== "InstancedMesh") {
  20407. this.releaseSubMeshes();
  20408. }
  20409. // Octree
  20410. var sceneOctree = this.getScene().selectionOctree;
  20411. if (sceneOctree !== undefined && sceneOctree !== null) {
  20412. var index = sceneOctree.dynamicContent.indexOf(this);
  20413. if (index !== -1) {
  20414. sceneOctree.dynamicContent.splice(index, 1);
  20415. }
  20416. }
  20417. // Query
  20418. var engine = this.getScene().getEngine();
  20419. if (this._occlusionQuery) {
  20420. this._isOcclusionQueryInProgress = false;
  20421. engine.deleteQuery(this._occlusionQuery);
  20422. this._occlusionQuery = null;
  20423. }
  20424. // Engine
  20425. engine.wipeCaches();
  20426. // Remove from scene
  20427. this.getScene().removeMesh(this);
  20428. if (disposeMaterialAndTextures) {
  20429. if (this.material) {
  20430. this.material.dispose(false, true);
  20431. }
  20432. }
  20433. if (!doNotRecurse) {
  20434. // Particles
  20435. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20436. if (this.getScene().particleSystems[index].emitter === this) {
  20437. this.getScene().particleSystems[index].dispose();
  20438. index--;
  20439. }
  20440. }
  20441. }
  20442. // facet data
  20443. if (this._facetDataEnabled) {
  20444. this.disableFacetData();
  20445. }
  20446. this.onAfterWorldMatrixUpdateObservable.clear();
  20447. this.onCollideObservable.clear();
  20448. this.onCollisionPositionChangeObservable.clear();
  20449. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20450. };
  20451. /**
  20452. * Adds the passed mesh as a child to the current mesh.
  20453. * Returns the AbstractMesh.
  20454. */
  20455. AbstractMesh.prototype.addChild = function (mesh) {
  20456. mesh.setParent(this);
  20457. return this;
  20458. };
  20459. /**
  20460. * Removes the passed mesh from the current mesh children list.
  20461. * Returns the AbstractMesh.
  20462. */
  20463. AbstractMesh.prototype.removeChild = function (mesh) {
  20464. mesh.setParent(null);
  20465. return this;
  20466. };
  20467. // Facet data
  20468. /**
  20469. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20470. * Returns the AbstractMesh.
  20471. */
  20472. AbstractMesh.prototype._initFacetData = function () {
  20473. if (!this._facetNormals) {
  20474. this._facetNormals = new Array();
  20475. }
  20476. if (!this._facetPositions) {
  20477. this._facetPositions = new Array();
  20478. }
  20479. if (!this._facetPartitioning) {
  20480. this._facetPartitioning = new Array();
  20481. }
  20482. this._facetNb = (this.getIndices().length / 3) | 0;
  20483. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20484. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20485. for (var f = 0; f < this._facetNb; f++) {
  20486. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20487. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20488. }
  20489. this._facetDataEnabled = true;
  20490. return this;
  20491. };
  20492. /**
  20493. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20494. * This method can be called within the render loop.
  20495. * 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.
  20496. * Returns the AbstractMesh.
  20497. */
  20498. AbstractMesh.prototype.updateFacetData = function () {
  20499. if (!this._facetDataEnabled) {
  20500. this._initFacetData();
  20501. }
  20502. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20503. var indices = this.getIndices();
  20504. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20505. var bInfo = this.getBoundingInfo();
  20506. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20507. // init arrays, matrix and sort function on first call
  20508. this._facetDepthSortEnabled = true;
  20509. if (indices instanceof Uint16Array) {
  20510. this._depthSortedIndices = new Uint16Array(indices);
  20511. }
  20512. else if (indices instanceof Uint32Array) {
  20513. this._depthSortedIndices = new Uint32Array(indices);
  20514. }
  20515. else {
  20516. var needs32bits = false;
  20517. for (var i = 0; i < indices.length; i++) {
  20518. if (indices[i] > 65535) {
  20519. needs32bits = true;
  20520. break;
  20521. }
  20522. }
  20523. if (needs32bits) {
  20524. this._depthSortedIndices = new Uint32Array(indices);
  20525. }
  20526. else {
  20527. this._depthSortedIndices = new Uint16Array(indices);
  20528. }
  20529. }
  20530. this._facetDepthSortFunction = function (f1, f2) {
  20531. return (f2.sqDistance - f1.sqDistance);
  20532. };
  20533. if (!this._facetDepthSortFrom) {
  20534. var camera = this.getScene().activeCamera;
  20535. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20536. }
  20537. this._depthSortedFacets = [];
  20538. for (var f = 0; f < this._facetNb; f++) {
  20539. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20540. this._depthSortedFacets.push(depthSortedFacet);
  20541. }
  20542. this._invertedMatrix = BABYLON.Matrix.Identity();
  20543. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20544. }
  20545. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20546. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20547. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20548. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20549. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20550. this._subDiv.max = this._partitioningSubdivisions;
  20551. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20552. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20553. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20554. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20555. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20556. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20557. // set the parameters for ComputeNormals()
  20558. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20559. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20560. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20561. this._facetParameters.bInfo = bInfo;
  20562. this._facetParameters.bbSize = this._bbSize;
  20563. this._facetParameters.subDiv = this._subDiv;
  20564. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20565. this._facetParameters.depthSort = this._facetDepthSort;
  20566. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20567. this.computeWorldMatrix(true);
  20568. this._worldMatrix.invertToRef(this._invertedMatrix);
  20569. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20570. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20571. }
  20572. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20573. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20574. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20575. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20576. var l = (this._depthSortedIndices.length / 3) | 0;
  20577. for (var f = 0; f < l; f++) {
  20578. var sind = this._depthSortedFacets[f].ind;
  20579. this._depthSortedIndices[f * 3] = indices[sind];
  20580. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20581. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20582. }
  20583. this.updateIndices(this._depthSortedIndices);
  20584. }
  20585. return this;
  20586. };
  20587. /**
  20588. * Returns the facetLocalNormals array.
  20589. * The normals are expressed in the mesh local space.
  20590. */
  20591. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20592. if (!this._facetNormals) {
  20593. this.updateFacetData();
  20594. }
  20595. return this._facetNormals;
  20596. };
  20597. /**
  20598. * Returns the facetLocalPositions array.
  20599. * The facet positions are expressed in the mesh local space.
  20600. */
  20601. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20602. if (!this._facetPositions) {
  20603. this.updateFacetData();
  20604. }
  20605. return this._facetPositions;
  20606. };
  20607. /**
  20608. * Returns the facetLocalPartioning array.
  20609. */
  20610. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20611. if (!this._facetPartitioning) {
  20612. this.updateFacetData();
  20613. }
  20614. return this._facetPartitioning;
  20615. };
  20616. /**
  20617. * Returns the i-th facet position in the world system.
  20618. * This method allocates a new Vector3 per call.
  20619. */
  20620. AbstractMesh.prototype.getFacetPosition = function (i) {
  20621. var pos = BABYLON.Vector3.Zero();
  20622. this.getFacetPositionToRef(i, pos);
  20623. return pos;
  20624. };
  20625. /**
  20626. * Sets the reference Vector3 with the i-th facet position in the world system.
  20627. * Returns the AbstractMesh.
  20628. */
  20629. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20630. var localPos = (this.getFacetLocalPositions())[i];
  20631. var world = this.getWorldMatrix();
  20632. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20633. return this;
  20634. };
  20635. /**
  20636. * Returns the i-th facet normal in the world system.
  20637. * This method allocates a new Vector3 per call.
  20638. */
  20639. AbstractMesh.prototype.getFacetNormal = function (i) {
  20640. var norm = BABYLON.Vector3.Zero();
  20641. this.getFacetNormalToRef(i, norm);
  20642. return norm;
  20643. };
  20644. /**
  20645. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20646. * Returns the AbstractMesh.
  20647. */
  20648. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20649. var localNorm = (this.getFacetLocalNormals())[i];
  20650. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20651. return this;
  20652. };
  20653. /**
  20654. * 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).
  20655. */
  20656. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20657. var bInfo = this.getBoundingInfo();
  20658. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20659. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20660. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20661. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20662. return null;
  20663. }
  20664. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20665. };
  20666. /**
  20667. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20668. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20669. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  20670. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20671. * 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.
  20672. */
  20673. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20674. if (checkFace === void 0) { checkFace = false; }
  20675. if (facing === void 0) { facing = true; }
  20676. var world = this.getWorldMatrix();
  20677. var invMat = BABYLON.Tmp.Matrix[5];
  20678. world.invertToRef(invMat);
  20679. var invVect = BABYLON.Tmp.Vector3[8];
  20680. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20681. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20682. if (projected) {
  20683. // tranform the local computed projected vector to world coordinates
  20684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20685. }
  20686. return closest;
  20687. };
  20688. /**
  20689. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20690. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20691. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  20692. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20693. * 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.
  20694. */
  20695. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20696. if (checkFace === void 0) { checkFace = false; }
  20697. if (facing === void 0) { facing = true; }
  20698. var closest = null;
  20699. var tmpx = 0.0;
  20700. var tmpy = 0.0;
  20701. var tmpz = 0.0;
  20702. var d = 0.0; // tmp dot facet normal * facet position
  20703. var t0 = 0.0;
  20704. var projx = 0.0;
  20705. var projy = 0.0;
  20706. var projz = 0.0;
  20707. // Get all the facets in the same partitioning block than (x, y, z)
  20708. var facetPositions = this.getFacetLocalPositions();
  20709. var facetNormals = this.getFacetLocalNormals();
  20710. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20711. if (!facetsInBlock) {
  20712. return null;
  20713. }
  20714. // Get the closest facet to (x, y, z)
  20715. var shortest = Number.MAX_VALUE; // init distance vars
  20716. var tmpDistance = shortest;
  20717. var fib; // current facet in the block
  20718. var norm; // current facet normal
  20719. var p0; // current facet barycenter position
  20720. // loop on all the facets in the current partitioning block
  20721. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20722. fib = facetsInBlock[idx];
  20723. norm = facetNormals[fib];
  20724. p0 = facetPositions[fib];
  20725. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20726. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20727. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20728. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20729. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20730. projx = x + norm.x * t0;
  20731. projy = y + norm.y * t0;
  20732. projz = z + norm.z * t0;
  20733. tmpx = projx - x;
  20734. tmpy = projy - y;
  20735. tmpz = projz - z;
  20736. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20737. if (tmpDistance < shortest) {
  20738. shortest = tmpDistance;
  20739. closest = fib;
  20740. if (projected) {
  20741. projected.x = projx;
  20742. projected.y = projy;
  20743. projected.z = projz;
  20744. }
  20745. }
  20746. }
  20747. }
  20748. return closest;
  20749. };
  20750. /**
  20751. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20752. */
  20753. AbstractMesh.prototype.getFacetDataParameters = function () {
  20754. return this._facetParameters;
  20755. };
  20756. /**
  20757. * Disables the feature FacetData and frees the related memory.
  20758. * Returns the AbstractMesh.
  20759. */
  20760. AbstractMesh.prototype.disableFacetData = function () {
  20761. if (this._facetDataEnabled) {
  20762. this._facetDataEnabled = false;
  20763. this._facetPositions = new Array();
  20764. this._facetNormals = new Array();
  20765. this._facetPartitioning = new Array();
  20766. this._facetParameters = null;
  20767. this._depthSortedIndices = new Uint32Array(0);
  20768. }
  20769. return this;
  20770. };
  20771. /**
  20772. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20773. * Returns the mesh.
  20774. */
  20775. AbstractMesh.prototype.updateIndices = function (indices) {
  20776. return this;
  20777. };
  20778. /**
  20779. * The mesh Geometry. Actually used by the Mesh object.
  20780. * Returns a blank geometry object.
  20781. */
  20782. /**
  20783. * Creates new normals data for the mesh.
  20784. * @param updatable.
  20785. */
  20786. AbstractMesh.prototype.createNormals = function (updatable) {
  20787. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20788. var indices = this.getIndices();
  20789. var normals;
  20790. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20791. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20792. }
  20793. else {
  20794. normals = [];
  20795. }
  20796. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20797. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20798. };
  20799. /**
  20800. * Align the mesh with a normal.
  20801. * Returns the mesh.
  20802. */
  20803. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20804. if (!upDirection) {
  20805. upDirection = BABYLON.Axis.Y;
  20806. }
  20807. var axisX = BABYLON.Tmp.Vector3[0];
  20808. var axisZ = BABYLON.Tmp.Vector3[1];
  20809. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20810. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20811. if (this.rotationQuaternion) {
  20812. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20813. }
  20814. else {
  20815. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20816. }
  20817. return this;
  20818. };
  20819. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20820. var engine = this.getEngine();
  20821. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20822. this._isOccluded = false;
  20823. return;
  20824. }
  20825. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20826. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20827. if (isOcclusionQueryAvailable) {
  20828. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20829. this._isOcclusionQueryInProgress = false;
  20830. this._occlusionInternalRetryCounter = 0;
  20831. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20832. }
  20833. else {
  20834. this._occlusionInternalRetryCounter++;
  20835. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20836. this._isOcclusionQueryInProgress = false;
  20837. this._occlusionInternalRetryCounter = 0;
  20838. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20839. // if strict continue the last state of the object.
  20840. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20841. }
  20842. else {
  20843. return;
  20844. }
  20845. }
  20846. }
  20847. var scene = this.getScene();
  20848. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20849. if (!this._occlusionQuery) {
  20850. this._occlusionQuery = engine.createQuery();
  20851. }
  20852. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20853. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20854. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20855. this._isOcclusionQueryInProgress = true;
  20856. };
  20857. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20858. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20859. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20860. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20861. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20862. return AbstractMesh;
  20863. }(BABYLON.TransformNode));
  20864. BABYLON.AbstractMesh = AbstractMesh;
  20865. })(BABYLON || (BABYLON = {}));
  20866. //# sourceMappingURL=babylon.abstractMesh.js.map
  20867. "use strict";
  20868. var BABYLON;
  20869. (function (BABYLON) {
  20870. /**
  20871. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20872. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20873. * 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.
  20874. */
  20875. var Light = /** @class */ (function (_super) {
  20876. __extends(Light, _super);
  20877. /**
  20878. * Creates a Light object in the scene.
  20879. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20880. * @param name The firendly name of the light
  20881. * @param scene The scene the light belongs too
  20882. */
  20883. function Light(name, scene) {
  20884. var _this = _super.call(this, name, scene) || this;
  20885. /**
  20886. * Diffuse gives the basic color to an object.
  20887. */
  20888. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20889. /**
  20890. * Specular produces a highlight color on an object.
  20891. * Note: This is note affecting PBR materials.
  20892. */
  20893. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20894. /**
  20895. * Strength of the light.
  20896. * Note: By default it is define in the framework own unit.
  20897. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20898. */
  20899. _this.intensity = 1.0;
  20900. /**
  20901. * Defines how far from the source the light is impacting in scene units.
  20902. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20903. */
  20904. _this.range = Number.MAX_VALUE;
  20905. /**
  20906. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20907. * of light.
  20908. */
  20909. _this._photometricScale = 1.0;
  20910. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20911. _this._radius = 0.00001;
  20912. /**
  20913. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20914. * exceeding the number allowed of the materials.
  20915. */
  20916. _this.renderPriority = 0;
  20917. /**
  20918. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20919. * the current shadow generator.
  20920. */
  20921. _this.shadowEnabled = true;
  20922. _this._excludeWithLayerMask = 0;
  20923. _this._includeOnlyWithLayerMask = 0;
  20924. _this._lightmapMode = 0;
  20925. /**
  20926. * @ignore Internal use only.
  20927. */
  20928. _this._excludedMeshesIds = new Array();
  20929. /**
  20930. * @ignore Internal use only.
  20931. */
  20932. _this._includedOnlyMeshesIds = new Array();
  20933. _this.getScene().addLight(_this);
  20934. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20935. _this._buildUniformLayout();
  20936. _this.includedOnlyMeshes = new Array();
  20937. _this.excludedMeshes = new Array();
  20938. _this._resyncMeshes();
  20939. return _this;
  20940. }
  20941. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20942. /**
  20943. * If every light affecting the material is in this lightmapMode,
  20944. * material.lightmapTexture adds or multiplies
  20945. * (depends on material.useLightmapAsShadowmap)
  20946. * after every other light calculations.
  20947. */
  20948. get: function () {
  20949. return Light._LIGHTMAP_DEFAULT;
  20950. },
  20951. enumerable: true,
  20952. configurable: true
  20953. });
  20954. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20955. /**
  20956. * material.lightmapTexture as only diffuse lighting from this light
  20957. * adds only specular lighting from this light
  20958. * adds dynamic shadows
  20959. */
  20960. get: function () {
  20961. return Light._LIGHTMAP_SPECULAR;
  20962. },
  20963. enumerable: true,
  20964. configurable: true
  20965. });
  20966. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20967. /**
  20968. * material.lightmapTexture as only lighting
  20969. * no light calculation from this light
  20970. * only adds dynamic shadows from this light
  20971. */
  20972. get: function () {
  20973. return Light._LIGHTMAP_SHADOWSONLY;
  20974. },
  20975. enumerable: true,
  20976. configurable: true
  20977. });
  20978. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20979. /**
  20980. * Each light type uses the default quantity according to its type:
  20981. * point/spot lights use luminous intensity
  20982. * directional lights use illuminance
  20983. */
  20984. get: function () {
  20985. return Light._INTENSITYMODE_AUTOMATIC;
  20986. },
  20987. enumerable: true,
  20988. configurable: true
  20989. });
  20990. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20991. /**
  20992. * lumen (lm)
  20993. */
  20994. get: function () {
  20995. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20996. },
  20997. enumerable: true,
  20998. configurable: true
  20999. });
  21000. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21001. /**
  21002. * candela (lm/sr)
  21003. */
  21004. get: function () {
  21005. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21006. },
  21007. enumerable: true,
  21008. configurable: true
  21009. });
  21010. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21011. /**
  21012. * lux (lm/m^2)
  21013. */
  21014. get: function () {
  21015. return Light._INTENSITYMODE_ILLUMINANCE;
  21016. },
  21017. enumerable: true,
  21018. configurable: true
  21019. });
  21020. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21021. /**
  21022. * nit (cd/m^2)
  21023. */
  21024. get: function () {
  21025. return Light._INTENSITYMODE_LUMINANCE;
  21026. },
  21027. enumerable: true,
  21028. configurable: true
  21029. });
  21030. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21031. /**
  21032. * Light type const id of the point light.
  21033. */
  21034. get: function () {
  21035. return Light._LIGHTTYPEID_POINTLIGHT;
  21036. },
  21037. enumerable: true,
  21038. configurable: true
  21039. });
  21040. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21041. /**
  21042. * Light type const id of the directional light.
  21043. */
  21044. get: function () {
  21045. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21046. },
  21047. enumerable: true,
  21048. configurable: true
  21049. });
  21050. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21051. /**
  21052. * Light type const id of the spot light.
  21053. */
  21054. get: function () {
  21055. return Light._LIGHTTYPEID_SPOTLIGHT;
  21056. },
  21057. enumerable: true,
  21058. configurable: true
  21059. });
  21060. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21061. /**
  21062. * Light type const id of the hemispheric light.
  21063. */
  21064. get: function () {
  21065. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21066. },
  21067. enumerable: true,
  21068. configurable: true
  21069. });
  21070. Object.defineProperty(Light.prototype, "intensityMode", {
  21071. /**
  21072. * Gets the photometric scale used to interpret the intensity.
  21073. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21074. */
  21075. get: function () {
  21076. return this._intensityMode;
  21077. },
  21078. /**
  21079. * Sets the photometric scale used to interpret the intensity.
  21080. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21081. */
  21082. set: function (value) {
  21083. this._intensityMode = value;
  21084. this._computePhotometricScale();
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. ;
  21090. ;
  21091. Object.defineProperty(Light.prototype, "radius", {
  21092. /**
  21093. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21094. */
  21095. get: function () {
  21096. return this._radius;
  21097. },
  21098. /**
  21099. * sets the light radius used by PBR Materials to simulate soft area lights.
  21100. */
  21101. set: function (value) {
  21102. this._radius = value;
  21103. this._computePhotometricScale();
  21104. },
  21105. enumerable: true,
  21106. configurable: true
  21107. });
  21108. ;
  21109. ;
  21110. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21111. /**
  21112. * Gets the only meshes impacted by this light.
  21113. */
  21114. get: function () {
  21115. return this._includedOnlyMeshes;
  21116. },
  21117. /**
  21118. * Sets the only meshes impacted by this light.
  21119. */
  21120. set: function (value) {
  21121. this._includedOnlyMeshes = value;
  21122. this._hookArrayForIncludedOnly(value);
  21123. },
  21124. enumerable: true,
  21125. configurable: true
  21126. });
  21127. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21128. /**
  21129. * Gets the meshes not impacted by this light.
  21130. */
  21131. get: function () {
  21132. return this._excludedMeshes;
  21133. },
  21134. /**
  21135. * Sets the meshes not impacted by this light.
  21136. */
  21137. set: function (value) {
  21138. this._excludedMeshes = value;
  21139. this._hookArrayForExcluded(value);
  21140. },
  21141. enumerable: true,
  21142. configurable: true
  21143. });
  21144. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21145. /**
  21146. * Gets the layer id use to find what meshes are not impacted by the light.
  21147. * Inactive if 0
  21148. */
  21149. get: function () {
  21150. return this._excludeWithLayerMask;
  21151. },
  21152. /**
  21153. * Sets the layer id use to find what meshes are not impacted by the light.
  21154. * Inactive if 0
  21155. */
  21156. set: function (value) {
  21157. this._excludeWithLayerMask = value;
  21158. this._resyncMeshes();
  21159. },
  21160. enumerable: true,
  21161. configurable: true
  21162. });
  21163. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21164. /**
  21165. * Gets the layer id use to find what meshes are impacted by the light.
  21166. * Inactive if 0
  21167. */
  21168. get: function () {
  21169. return this._includeOnlyWithLayerMask;
  21170. },
  21171. /**
  21172. * Sets the layer id use to find what meshes are impacted by the light.
  21173. * Inactive if 0
  21174. */
  21175. set: function (value) {
  21176. this._includeOnlyWithLayerMask = value;
  21177. this._resyncMeshes();
  21178. },
  21179. enumerable: true,
  21180. configurable: true
  21181. });
  21182. Object.defineProperty(Light.prototype, "lightmapMode", {
  21183. /**
  21184. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21185. */
  21186. get: function () {
  21187. return this._lightmapMode;
  21188. },
  21189. /**
  21190. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21191. */
  21192. set: function (value) {
  21193. if (this._lightmapMode === value) {
  21194. return;
  21195. }
  21196. this._lightmapMode = value;
  21197. this._markMeshesAsLightDirty();
  21198. },
  21199. enumerable: true,
  21200. configurable: true
  21201. });
  21202. /**
  21203. * Returns the string "Light".
  21204. * @returns the class name
  21205. */
  21206. Light.prototype.getClassName = function () {
  21207. return "Light";
  21208. };
  21209. /**
  21210. * Converts the light information to a readable string for debug purpose.
  21211. * @param fullDetails Supports for multiple levels of logging within scene loading
  21212. * @returns the human readable light info
  21213. */
  21214. Light.prototype.toString = function (fullDetails) {
  21215. var ret = "Name: " + this.name;
  21216. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21217. if (this.animations) {
  21218. for (var i = 0; i < this.animations.length; i++) {
  21219. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21220. }
  21221. }
  21222. if (fullDetails) {
  21223. }
  21224. return ret;
  21225. };
  21226. /**
  21227. * Set the enabled state of this node.
  21228. * @param value - the new enabled state
  21229. */
  21230. Light.prototype.setEnabled = function (value) {
  21231. _super.prototype.setEnabled.call(this, value);
  21232. this._resyncMeshes();
  21233. };
  21234. /**
  21235. * Returns the Light associated shadow generator if any.
  21236. * @return the associated shadow generator.
  21237. */
  21238. Light.prototype.getShadowGenerator = function () {
  21239. return this._shadowGenerator;
  21240. };
  21241. /**
  21242. * Returns a Vector3, the absolute light position in the World.
  21243. * @returns the world space position of the light
  21244. */
  21245. Light.prototype.getAbsolutePosition = function () {
  21246. return BABYLON.Vector3.Zero();
  21247. };
  21248. /**
  21249. * Specifies if the light will affect the passed mesh.
  21250. * @param mesh The mesh to test against the light
  21251. * @return true the mesh is affected otherwise, false.
  21252. */
  21253. Light.prototype.canAffectMesh = function (mesh) {
  21254. if (!mesh) {
  21255. return true;
  21256. }
  21257. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21258. return false;
  21259. }
  21260. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21261. return false;
  21262. }
  21263. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21264. return false;
  21265. }
  21266. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21267. return false;
  21268. }
  21269. return true;
  21270. };
  21271. /**
  21272. * Computes and Returns the light World matrix.
  21273. * @returns the world matrix
  21274. */
  21275. Light.prototype.getWorldMatrix = function () {
  21276. this._currentRenderId = this.getScene().getRenderId();
  21277. this._childRenderId = this._currentRenderId;
  21278. var worldMatrix = this._getWorldMatrix();
  21279. if (this.parent && this.parent.getWorldMatrix) {
  21280. if (!this._parentedWorldMatrix) {
  21281. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21282. }
  21283. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21284. this._markSyncedWithParent();
  21285. return this._parentedWorldMatrix;
  21286. }
  21287. return worldMatrix;
  21288. };
  21289. /**
  21290. * Sort function to order lights for rendering.
  21291. * @param a First Light object to compare to second.
  21292. * @param b Second Light object to compare first.
  21293. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21294. */
  21295. Light.CompareLightsPriority = function (a, b) {
  21296. //shadow-casting lights have priority over non-shadow-casting lights
  21297. //the renderPrioirty is a secondary sort criterion
  21298. if (a.shadowEnabled !== b.shadowEnabled) {
  21299. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21300. }
  21301. return b.renderPriority - a.renderPriority;
  21302. };
  21303. /**
  21304. * Releases resources associated with this node.
  21305. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21306. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21307. */
  21308. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21309. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21310. if (this._shadowGenerator) {
  21311. this._shadowGenerator.dispose();
  21312. this._shadowGenerator = null;
  21313. }
  21314. // Animations
  21315. this.getScene().stopAnimation(this);
  21316. // Remove from meshes
  21317. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21318. var mesh = _a[_i];
  21319. mesh._removeLightSource(this);
  21320. }
  21321. this._uniformBuffer.dispose();
  21322. // Remove from scene
  21323. this.getScene().removeLight(this);
  21324. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21325. };
  21326. /**
  21327. * Returns the light type ID (integer).
  21328. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21329. */
  21330. Light.prototype.getTypeID = function () {
  21331. return 0;
  21332. };
  21333. /**
  21334. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21335. * @returns the scaled intensity in intensity mode unit
  21336. */
  21337. Light.prototype.getScaledIntensity = function () {
  21338. return this._photometricScale * this.intensity;
  21339. };
  21340. /**
  21341. * Returns a new Light object, named "name", from the current one.
  21342. * @param name The name of the cloned light
  21343. * @returns the new created light
  21344. */
  21345. Light.prototype.clone = function (name) {
  21346. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21347. if (!constructor) {
  21348. return null;
  21349. }
  21350. return BABYLON.SerializationHelper.Clone(constructor, this);
  21351. };
  21352. /**
  21353. * Serializes the current light into a Serialization object.
  21354. * @returns the serialized object.
  21355. */
  21356. Light.prototype.serialize = function () {
  21357. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21358. // Type
  21359. serializationObject.type = this.getTypeID();
  21360. // Parent
  21361. if (this.parent) {
  21362. serializationObject.parentId = this.parent.id;
  21363. }
  21364. // Inclusion / exclusions
  21365. if (this.excludedMeshes.length > 0) {
  21366. serializationObject.excludedMeshesIds = [];
  21367. this.excludedMeshes.forEach(function (mesh) {
  21368. serializationObject.excludedMeshesIds.push(mesh.id);
  21369. });
  21370. }
  21371. if (this.includedOnlyMeshes.length > 0) {
  21372. serializationObject.includedOnlyMeshesIds = [];
  21373. this.includedOnlyMeshes.forEach(function (mesh) {
  21374. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21375. });
  21376. }
  21377. // Animations
  21378. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21379. serializationObject.ranges = this.serializeAnimationRanges();
  21380. return serializationObject;
  21381. };
  21382. /**
  21383. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21384. * This new light is named "name" and added to the passed scene.
  21385. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21386. * @param name The friendly name of the light
  21387. * @param scene The scene the new light will belong to
  21388. * @returns the constructor function
  21389. */
  21390. Light.GetConstructorFromName = function (type, name, scene) {
  21391. switch (type) {
  21392. case 0:
  21393. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21394. case 1:
  21395. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21396. case 2:
  21397. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21398. case 3:
  21399. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21400. }
  21401. return null;
  21402. };
  21403. /**
  21404. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21405. * @param parsedLight The JSON representation of the light
  21406. * @param scene The scene to create the parsed light in
  21407. * @returns the created light after parsing
  21408. */
  21409. Light.Parse = function (parsedLight, scene) {
  21410. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21411. if (!constructor) {
  21412. return null;
  21413. }
  21414. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21415. // Inclusion / exclusions
  21416. if (parsedLight.excludedMeshesIds) {
  21417. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21418. }
  21419. if (parsedLight.includedOnlyMeshesIds) {
  21420. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21421. }
  21422. // Parent
  21423. if (parsedLight.parentId) {
  21424. light._waitingParentId = parsedLight.parentId;
  21425. }
  21426. // Animations
  21427. if (parsedLight.animations) {
  21428. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21429. var parsedAnimation = parsedLight.animations[animationIndex];
  21430. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21431. }
  21432. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21433. }
  21434. if (parsedLight.autoAnimate) {
  21435. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21436. }
  21437. return light;
  21438. };
  21439. Light.prototype._hookArrayForExcluded = function (array) {
  21440. var _this = this;
  21441. var oldPush = array.push;
  21442. array.push = function () {
  21443. var items = [];
  21444. for (var _i = 0; _i < arguments.length; _i++) {
  21445. items[_i] = arguments[_i];
  21446. }
  21447. var result = oldPush.apply(array, items);
  21448. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21449. var item = items_1[_a];
  21450. item._resyncLighSource(_this);
  21451. }
  21452. return result;
  21453. };
  21454. var oldSplice = array.splice;
  21455. array.splice = function (index, deleteCount) {
  21456. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21457. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21458. var item = deleted_1[_i];
  21459. item._resyncLighSource(_this);
  21460. }
  21461. return deleted;
  21462. };
  21463. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21464. var item = array_1[_i];
  21465. item._resyncLighSource(this);
  21466. }
  21467. };
  21468. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21469. var _this = this;
  21470. var oldPush = array.push;
  21471. array.push = function () {
  21472. var items = [];
  21473. for (var _i = 0; _i < arguments.length; _i++) {
  21474. items[_i] = arguments[_i];
  21475. }
  21476. var result = oldPush.apply(array, items);
  21477. _this._resyncMeshes();
  21478. return result;
  21479. };
  21480. var oldSplice = array.splice;
  21481. array.splice = function (index, deleteCount) {
  21482. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21483. _this._resyncMeshes();
  21484. return deleted;
  21485. };
  21486. this._resyncMeshes();
  21487. };
  21488. Light.prototype._resyncMeshes = function () {
  21489. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21490. var mesh = _a[_i];
  21491. mesh._resyncLighSource(this);
  21492. }
  21493. };
  21494. /**
  21495. * Forces the meshes to update their light related information in their rendering used effects
  21496. * @ignore Internal Use Only
  21497. */
  21498. Light.prototype._markMeshesAsLightDirty = function () {
  21499. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21500. var mesh = _a[_i];
  21501. if (mesh._lightSources.indexOf(this) !== -1) {
  21502. mesh._markSubMeshesAsLightDirty();
  21503. }
  21504. }
  21505. };
  21506. /**
  21507. * Recomputes the cached photometric scale if needed.
  21508. */
  21509. Light.prototype._computePhotometricScale = function () {
  21510. this._photometricScale = this._getPhotometricScale();
  21511. this.getScene().resetCachedMaterial();
  21512. };
  21513. /**
  21514. * Returns the Photometric Scale according to the light type and intensity mode.
  21515. */
  21516. Light.prototype._getPhotometricScale = function () {
  21517. var photometricScale = 0.0;
  21518. var lightTypeID = this.getTypeID();
  21519. //get photometric mode
  21520. var photometricMode = this.intensityMode;
  21521. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21522. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21523. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21524. }
  21525. else {
  21526. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21527. }
  21528. }
  21529. //compute photometric scale
  21530. switch (lightTypeID) {
  21531. case Light.LIGHTTYPEID_POINTLIGHT:
  21532. case Light.LIGHTTYPEID_SPOTLIGHT:
  21533. switch (photometricMode) {
  21534. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21535. photometricScale = 1.0 / (4.0 * Math.PI);
  21536. break;
  21537. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21538. photometricScale = 1.0;
  21539. break;
  21540. case Light.INTENSITYMODE_LUMINANCE:
  21541. photometricScale = this.radius * this.radius;
  21542. break;
  21543. }
  21544. break;
  21545. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21546. switch (photometricMode) {
  21547. case Light.INTENSITYMODE_ILLUMINANCE:
  21548. photometricScale = 1.0;
  21549. break;
  21550. case Light.INTENSITYMODE_LUMINANCE:
  21551. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21552. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21553. var apexAngleRadians = this.radius;
  21554. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21555. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21556. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21557. photometricScale = solidAngle;
  21558. break;
  21559. }
  21560. break;
  21561. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21562. // No fall off in hemisperic light.
  21563. photometricScale = 1.0;
  21564. break;
  21565. }
  21566. return photometricScale;
  21567. };
  21568. /**
  21569. * Reorder the light in the scene according to their defined priority.
  21570. * @ignore Internal Use Only
  21571. */
  21572. Light.prototype._reorderLightsInScene = function () {
  21573. var scene = this.getScene();
  21574. if (this._renderPriority != 0) {
  21575. scene.requireLightSorting = true;
  21576. }
  21577. this.getScene().sortLightsByPriority();
  21578. };
  21579. //lightmapMode Consts
  21580. Light._LIGHTMAP_DEFAULT = 0;
  21581. Light._LIGHTMAP_SPECULAR = 1;
  21582. Light._LIGHTMAP_SHADOWSONLY = 2;
  21583. // Intensity Mode Consts
  21584. Light._INTENSITYMODE_AUTOMATIC = 0;
  21585. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21586. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21587. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21588. Light._INTENSITYMODE_LUMINANCE = 4;
  21589. // Light types ids const.
  21590. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21591. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21592. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21593. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21594. __decorate([
  21595. BABYLON.serializeAsColor3()
  21596. ], Light.prototype, "diffuse", void 0);
  21597. __decorate([
  21598. BABYLON.serializeAsColor3()
  21599. ], Light.prototype, "specular", void 0);
  21600. __decorate([
  21601. BABYLON.serialize()
  21602. ], Light.prototype, "intensity", void 0);
  21603. __decorate([
  21604. BABYLON.serialize()
  21605. ], Light.prototype, "range", void 0);
  21606. __decorate([
  21607. BABYLON.serialize()
  21608. ], Light.prototype, "intensityMode", null);
  21609. __decorate([
  21610. BABYLON.serialize()
  21611. ], Light.prototype, "radius", null);
  21612. __decorate([
  21613. BABYLON.serialize()
  21614. ], Light.prototype, "_renderPriority", void 0);
  21615. __decorate([
  21616. BABYLON.expandToProperty("_reorderLightsInScene")
  21617. ], Light.prototype, "renderPriority", void 0);
  21618. __decorate([
  21619. BABYLON.serialize()
  21620. ], Light.prototype, "shadowEnabled", void 0);
  21621. __decorate([
  21622. BABYLON.serialize("excludeWithLayerMask")
  21623. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21624. __decorate([
  21625. BABYLON.serialize("includeOnlyWithLayerMask")
  21626. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21627. __decorate([
  21628. BABYLON.serialize("lightmapMode")
  21629. ], Light.prototype, "_lightmapMode", void 0);
  21630. return Light;
  21631. }(BABYLON.Node));
  21632. BABYLON.Light = Light;
  21633. })(BABYLON || (BABYLON = {}));
  21634. //# sourceMappingURL=babylon.light.js.map
  21635. "use strict";
  21636. var BABYLON;
  21637. (function (BABYLON) {
  21638. var Camera = /** @class */ (function (_super) {
  21639. __extends(Camera, _super);
  21640. function Camera(name, position, scene) {
  21641. var _this = _super.call(this, name, scene) || this;
  21642. /**
  21643. * The vector the camera should consider as up.
  21644. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21645. */
  21646. _this.upVector = BABYLON.Vector3.Up();
  21647. _this.orthoLeft = null;
  21648. _this.orthoRight = null;
  21649. _this.orthoBottom = null;
  21650. _this.orthoTop = null;
  21651. /**
  21652. * FOV is set in Radians. (default is 0.8)
  21653. */
  21654. _this.fov = 0.8;
  21655. _this.minZ = 1;
  21656. _this.maxZ = 10000.0;
  21657. _this.inertia = 0.9;
  21658. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21659. _this.isIntermediate = false;
  21660. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21661. /**
  21662. * Restricts the camera to viewing objects with the same layerMask.
  21663. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21664. */
  21665. _this.layerMask = 0x0FFFFFFF;
  21666. /**
  21667. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21668. */
  21669. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21670. // Camera rig members
  21671. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21672. _this._rigCameras = new Array();
  21673. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21674. _this._skipRendering = false;
  21675. _this.customRenderTargets = new Array();
  21676. // Observables
  21677. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21678. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21679. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21680. _this.onRestoreStateObservable = new BABYLON.Observable();
  21681. // Cache
  21682. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21683. _this._projectionMatrix = new BABYLON.Matrix();
  21684. _this._doNotComputeProjectionMatrix = false;
  21685. _this._postProcesses = new Array();
  21686. _this._transformMatrix = BABYLON.Matrix.Zero();
  21687. _this._activeMeshes = new BABYLON.SmartArray(256);
  21688. _this._globalPosition = BABYLON.Vector3.Zero();
  21689. _this._refreshFrustumPlanes = true;
  21690. _this.getScene().addCamera(_this);
  21691. if (!_this.getScene().activeCamera) {
  21692. _this.getScene().activeCamera = _this;
  21693. }
  21694. _this.position = position;
  21695. return _this;
  21696. }
  21697. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21698. get: function () {
  21699. return Camera._PERSPECTIVE_CAMERA;
  21700. },
  21701. enumerable: true,
  21702. configurable: true
  21703. });
  21704. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21705. get: function () {
  21706. return Camera._ORTHOGRAPHIC_CAMERA;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21712. /**
  21713. * This is the default FOV mode for perspective cameras.
  21714. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21715. *
  21716. */
  21717. get: function () {
  21718. return Camera._FOVMODE_VERTICAL_FIXED;
  21719. },
  21720. enumerable: true,
  21721. configurable: true
  21722. });
  21723. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21724. /**
  21725. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21726. *
  21727. */
  21728. get: function () {
  21729. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21735. get: function () {
  21736. return Camera._RIG_MODE_NONE;
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21742. get: function () {
  21743. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21749. get: function () {
  21750. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21751. },
  21752. enumerable: true,
  21753. configurable: true
  21754. });
  21755. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21756. get: function () {
  21757. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21758. },
  21759. enumerable: true,
  21760. configurable: true
  21761. });
  21762. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21763. get: function () {
  21764. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21770. get: function () {
  21771. return Camera._RIG_MODE_VR;
  21772. },
  21773. enumerable: true,
  21774. configurable: true
  21775. });
  21776. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21777. get: function () {
  21778. return Camera._RIG_MODE_WEBVR;
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. /**
  21784. * Store current camera state (fov, position, etc..)
  21785. */
  21786. Camera.prototype.storeState = function () {
  21787. this._stateStored = true;
  21788. this._storedFov = this.fov;
  21789. return this;
  21790. };
  21791. /**
  21792. * Restores the camera state values if it has been stored. You must call storeState() first
  21793. */
  21794. Camera.prototype._restoreStateValues = function () {
  21795. if (!this._stateStored) {
  21796. return false;
  21797. }
  21798. this.fov = this._storedFov;
  21799. return true;
  21800. };
  21801. /**
  21802. * Restored camera state. You must call storeState() first
  21803. */
  21804. Camera.prototype.restoreState = function () {
  21805. if (this._restoreStateValues()) {
  21806. this.onRestoreStateObservable.notifyObservers(this);
  21807. return true;
  21808. }
  21809. return false;
  21810. };
  21811. Camera.prototype.getClassName = function () {
  21812. return "Camera";
  21813. };
  21814. /**
  21815. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21816. */
  21817. Camera.prototype.toString = function (fullDetails) {
  21818. var ret = "Name: " + this.name;
  21819. ret += ", type: " + this.getClassName();
  21820. if (this.animations) {
  21821. for (var i = 0; i < this.animations.length; i++) {
  21822. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21823. }
  21824. }
  21825. if (fullDetails) {
  21826. }
  21827. return ret;
  21828. };
  21829. Object.defineProperty(Camera.prototype, "globalPosition", {
  21830. get: function () {
  21831. return this._globalPosition;
  21832. },
  21833. enumerable: true,
  21834. configurable: true
  21835. });
  21836. Camera.prototype.getActiveMeshes = function () {
  21837. return this._activeMeshes;
  21838. };
  21839. Camera.prototype.isActiveMesh = function (mesh) {
  21840. return (this._activeMeshes.indexOf(mesh) !== -1);
  21841. };
  21842. /**
  21843. * Is this camera ready to be used/rendered
  21844. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21845. * @return true if the camera is ready
  21846. */
  21847. Camera.prototype.isReady = function (completeCheck) {
  21848. if (completeCheck === void 0) { completeCheck = false; }
  21849. if (completeCheck) {
  21850. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21851. var pp = _a[_i];
  21852. if (pp && !pp.isReady()) {
  21853. return false;
  21854. }
  21855. }
  21856. }
  21857. return _super.prototype.isReady.call(this, completeCheck);
  21858. };
  21859. //Cache
  21860. Camera.prototype._initCache = function () {
  21861. _super.prototype._initCache.call(this);
  21862. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21863. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21864. this._cache.mode = undefined;
  21865. this._cache.minZ = undefined;
  21866. this._cache.maxZ = undefined;
  21867. this._cache.fov = undefined;
  21868. this._cache.fovMode = undefined;
  21869. this._cache.aspectRatio = undefined;
  21870. this._cache.orthoLeft = undefined;
  21871. this._cache.orthoRight = undefined;
  21872. this._cache.orthoBottom = undefined;
  21873. this._cache.orthoTop = undefined;
  21874. this._cache.renderWidth = undefined;
  21875. this._cache.renderHeight = undefined;
  21876. };
  21877. Camera.prototype._updateCache = function (ignoreParentClass) {
  21878. if (!ignoreParentClass) {
  21879. _super.prototype._updateCache.call(this);
  21880. }
  21881. this._cache.position.copyFrom(this.position);
  21882. this._cache.upVector.copyFrom(this.upVector);
  21883. };
  21884. // Synchronized
  21885. Camera.prototype._isSynchronized = function () {
  21886. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21887. };
  21888. Camera.prototype._isSynchronizedViewMatrix = function () {
  21889. if (!_super.prototype._isSynchronized.call(this))
  21890. return false;
  21891. return this._cache.position.equals(this.position)
  21892. && this._cache.upVector.equals(this.upVector)
  21893. && this.isSynchronizedWithParent();
  21894. };
  21895. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21896. var check = this._cache.mode === this.mode
  21897. && this._cache.minZ === this.minZ
  21898. && this._cache.maxZ === this.maxZ;
  21899. if (!check) {
  21900. return false;
  21901. }
  21902. var engine = this.getEngine();
  21903. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21904. check = this._cache.fov === this.fov
  21905. && this._cache.fovMode === this.fovMode
  21906. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21907. }
  21908. else {
  21909. check = this._cache.orthoLeft === this.orthoLeft
  21910. && this._cache.orthoRight === this.orthoRight
  21911. && this._cache.orthoBottom === this.orthoBottom
  21912. && this._cache.orthoTop === this.orthoTop
  21913. && this._cache.renderWidth === engine.getRenderWidth()
  21914. && this._cache.renderHeight === engine.getRenderHeight();
  21915. }
  21916. return check;
  21917. };
  21918. // Controls
  21919. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21920. };
  21921. Camera.prototype.detachControl = function (element) {
  21922. };
  21923. Camera.prototype.update = function () {
  21924. this._checkInputs();
  21925. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21926. this._updateRigCameras();
  21927. }
  21928. };
  21929. Camera.prototype._checkInputs = function () {
  21930. this.onAfterCheckInputsObservable.notifyObservers(this);
  21931. };
  21932. Object.defineProperty(Camera.prototype, "rigCameras", {
  21933. get: function () {
  21934. return this._rigCameras;
  21935. },
  21936. enumerable: true,
  21937. configurable: true
  21938. });
  21939. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21940. get: function () {
  21941. return this._rigPostProcess;
  21942. },
  21943. enumerable: true,
  21944. configurable: true
  21945. });
  21946. /**
  21947. * Internal, gets the first post proces.
  21948. * @returns the first post process to be run on this camera.
  21949. */
  21950. Camera.prototype._getFirstPostProcess = function () {
  21951. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  21952. if (this._postProcesses[ppIndex] !== null) {
  21953. return this._postProcesses[ppIndex];
  21954. }
  21955. }
  21956. return null;
  21957. };
  21958. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21959. // invalidate framebuffer
  21960. var firstPostProcess = this._getFirstPostProcess();
  21961. if (firstPostProcess) {
  21962. firstPostProcess.markTextureDirty();
  21963. }
  21964. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21965. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21966. var cam = this._rigCameras[i];
  21967. var rigPostProcess = cam._rigPostProcess;
  21968. // for VR rig, there does not have to be a post process
  21969. if (rigPostProcess) {
  21970. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21971. if (isPass) {
  21972. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21973. cam.isIntermediate = this._postProcesses.length === 0;
  21974. }
  21975. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21976. rigPostProcess.markTextureDirty();
  21977. }
  21978. else {
  21979. cam._postProcesses = this._postProcesses.slice(0);
  21980. }
  21981. }
  21982. };
  21983. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21984. if (insertAt === void 0) { insertAt = null; }
  21985. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21986. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21987. return 0;
  21988. }
  21989. if (insertAt == null || insertAt < 0) {
  21990. this._postProcesses.push(postProcess);
  21991. }
  21992. else if (this._postProcesses[insertAt] === null) {
  21993. this._postProcesses[insertAt] = postProcess;
  21994. }
  21995. else {
  21996. this._postProcesses.splice(insertAt, 0, postProcess);
  21997. }
  21998. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21999. return this._postProcesses.indexOf(postProcess);
  22000. };
  22001. Camera.prototype.detachPostProcess = function (postProcess) {
  22002. var idx = this._postProcesses.indexOf(postProcess);
  22003. if (idx !== -1) {
  22004. this._postProcesses[idx] = null;
  22005. }
  22006. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22007. };
  22008. Camera.prototype.getWorldMatrix = function () {
  22009. if (!this._worldMatrix) {
  22010. this._worldMatrix = BABYLON.Matrix.Identity();
  22011. }
  22012. var viewMatrix = this.getViewMatrix();
  22013. viewMatrix.invertToRef(this._worldMatrix);
  22014. return this._worldMatrix;
  22015. };
  22016. Camera.prototype._getViewMatrix = function () {
  22017. return BABYLON.Matrix.Identity();
  22018. };
  22019. Camera.prototype.getViewMatrix = function (force) {
  22020. if (!force && this._isSynchronizedViewMatrix()) {
  22021. return this._computedViewMatrix;
  22022. }
  22023. this.updateCache();
  22024. this._computedViewMatrix = this._getViewMatrix();
  22025. this._currentRenderId = this.getScene().getRenderId();
  22026. this._childRenderId = this._currentRenderId;
  22027. this._refreshFrustumPlanes = true;
  22028. if (!this.parent || !this.parent.getWorldMatrix) {
  22029. this._globalPosition.copyFrom(this.position);
  22030. }
  22031. else {
  22032. if (!this._worldMatrix) {
  22033. this._worldMatrix = BABYLON.Matrix.Identity();
  22034. }
  22035. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22036. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  22037. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  22038. this._computedViewMatrix.invert();
  22039. this._markSyncedWithParent();
  22040. }
  22041. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22042. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22043. }
  22044. this.onViewMatrixChangedObservable.notifyObservers(this);
  22045. return this._computedViewMatrix;
  22046. };
  22047. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22048. this._doNotComputeProjectionMatrix = true;
  22049. if (projection !== undefined) {
  22050. this._projectionMatrix = projection;
  22051. }
  22052. };
  22053. ;
  22054. Camera.prototype.unfreezeProjectionMatrix = function () {
  22055. this._doNotComputeProjectionMatrix = false;
  22056. };
  22057. ;
  22058. Camera.prototype.getProjectionMatrix = function (force) {
  22059. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22060. return this._projectionMatrix;
  22061. }
  22062. // Cache
  22063. this._cache.mode = this.mode;
  22064. this._cache.minZ = this.minZ;
  22065. this._cache.maxZ = this.maxZ;
  22066. // Matrix
  22067. this._refreshFrustumPlanes = true;
  22068. var engine = this.getEngine();
  22069. var scene = this.getScene();
  22070. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22071. this._cache.fov = this.fov;
  22072. this._cache.fovMode = this.fovMode;
  22073. this._cache.aspectRatio = engine.getAspectRatio(this);
  22074. if (this.minZ <= 0) {
  22075. this.minZ = 0.1;
  22076. }
  22077. if (scene.useRightHandedSystem) {
  22078. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22079. }
  22080. else {
  22081. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22082. }
  22083. }
  22084. else {
  22085. var halfWidth = engine.getRenderWidth() / 2.0;
  22086. var halfHeight = engine.getRenderHeight() / 2.0;
  22087. if (scene.useRightHandedSystem) {
  22088. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22089. }
  22090. else {
  22091. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22092. }
  22093. this._cache.orthoLeft = this.orthoLeft;
  22094. this._cache.orthoRight = this.orthoRight;
  22095. this._cache.orthoBottom = this.orthoBottom;
  22096. this._cache.orthoTop = this.orthoTop;
  22097. this._cache.renderWidth = engine.getRenderWidth();
  22098. this._cache.renderHeight = engine.getRenderHeight();
  22099. }
  22100. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22101. return this._projectionMatrix;
  22102. };
  22103. Camera.prototype.getTranformationMatrix = function () {
  22104. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22105. return this._transformMatrix;
  22106. };
  22107. Camera.prototype.updateFrustumPlanes = function () {
  22108. if (!this._refreshFrustumPlanes) {
  22109. return;
  22110. }
  22111. this.getTranformationMatrix();
  22112. if (!this._frustumPlanes) {
  22113. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22114. }
  22115. else {
  22116. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22117. }
  22118. this._refreshFrustumPlanes = false;
  22119. };
  22120. Camera.prototype.isInFrustum = function (target) {
  22121. this.updateFrustumPlanes();
  22122. return target.isInFrustum(this._frustumPlanes);
  22123. };
  22124. Camera.prototype.isCompletelyInFrustum = function (target) {
  22125. this.updateFrustumPlanes();
  22126. return target.isCompletelyInFrustum(this._frustumPlanes);
  22127. };
  22128. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22129. if (length === void 0) { length = 100; }
  22130. if (!transform) {
  22131. transform = this.getWorldMatrix();
  22132. }
  22133. if (!origin) {
  22134. origin = this.position;
  22135. }
  22136. var forward = new BABYLON.Vector3(0, 0, 1);
  22137. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22138. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22139. return new BABYLON.Ray(origin, direction, length);
  22140. };
  22141. /**
  22142. * Releases resources associated with this node.
  22143. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22144. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22145. */
  22146. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22147. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22148. // Observables
  22149. this.onViewMatrixChangedObservable.clear();
  22150. this.onProjectionMatrixChangedObservable.clear();
  22151. this.onAfterCheckInputsObservable.clear();
  22152. this.onRestoreStateObservable.clear();
  22153. // Inputs
  22154. if (this.inputs) {
  22155. this.inputs.clear();
  22156. }
  22157. // Animations
  22158. this.getScene().stopAnimation(this);
  22159. // Remove from scene
  22160. this.getScene().removeCamera(this);
  22161. while (this._rigCameras.length > 0) {
  22162. var camera = this._rigCameras.pop();
  22163. if (camera) {
  22164. camera.dispose();
  22165. }
  22166. }
  22167. // Postprocesses
  22168. if (this._rigPostProcess) {
  22169. this._rigPostProcess.dispose(this);
  22170. this._rigPostProcess = null;
  22171. this._postProcesses = [];
  22172. }
  22173. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22174. this._rigPostProcess = null;
  22175. this._postProcesses = [];
  22176. }
  22177. else {
  22178. var i = this._postProcesses.length;
  22179. while (--i >= 0) {
  22180. var postProcess = this._postProcesses[i];
  22181. if (postProcess) {
  22182. postProcess.dispose(this);
  22183. }
  22184. }
  22185. }
  22186. // Render targets
  22187. var i = this.customRenderTargets.length;
  22188. while (--i >= 0) {
  22189. this.customRenderTargets[i].dispose();
  22190. }
  22191. this.customRenderTargets = [];
  22192. // Active Meshes
  22193. this._activeMeshes.dispose();
  22194. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22195. };
  22196. Object.defineProperty(Camera.prototype, "leftCamera", {
  22197. // ---- Camera rigs section ----
  22198. get: function () {
  22199. if (this._rigCameras.length < 1) {
  22200. return null;
  22201. }
  22202. return this._rigCameras[0];
  22203. },
  22204. enumerable: true,
  22205. configurable: true
  22206. });
  22207. Object.defineProperty(Camera.prototype, "rightCamera", {
  22208. get: function () {
  22209. if (this._rigCameras.length < 2) {
  22210. return null;
  22211. }
  22212. return this._rigCameras[1];
  22213. },
  22214. enumerable: true,
  22215. configurable: true
  22216. });
  22217. Camera.prototype.getLeftTarget = function () {
  22218. if (this._rigCameras.length < 1) {
  22219. return null;
  22220. }
  22221. return this._rigCameras[0].getTarget();
  22222. };
  22223. Camera.prototype.getRightTarget = function () {
  22224. if (this._rigCameras.length < 2) {
  22225. return null;
  22226. }
  22227. return this._rigCameras[1].getTarget();
  22228. };
  22229. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22230. if (this.cameraRigMode === mode) {
  22231. return;
  22232. }
  22233. while (this._rigCameras.length > 0) {
  22234. var camera = this._rigCameras.pop();
  22235. if (camera) {
  22236. camera.dispose();
  22237. }
  22238. }
  22239. this.cameraRigMode = mode;
  22240. this._cameraRigParams = {};
  22241. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22242. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22243. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22244. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22245. // create the rig cameras, unless none
  22246. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22247. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22248. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22249. if (leftCamera && rightCamera) {
  22250. this._rigCameras.push(leftCamera);
  22251. this._rigCameras.push(rightCamera);
  22252. }
  22253. }
  22254. switch (this.cameraRigMode) {
  22255. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22256. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22257. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22258. break;
  22259. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22260. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22261. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22262. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22263. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22264. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22265. break;
  22266. case Camera.RIG_MODE_VR:
  22267. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22268. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22269. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22270. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22271. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22272. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22273. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22274. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22275. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22276. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22277. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22278. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22279. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22280. if (metrics.compensateDistortion) {
  22281. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22282. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22283. }
  22284. break;
  22285. case Camera.RIG_MODE_WEBVR:
  22286. if (rigParams.vrDisplay) {
  22287. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22288. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22289. //Left eye
  22290. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22291. this._rigCameras[0].setCameraRigParameter("left", true);
  22292. //leaving this for future reference
  22293. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22294. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22295. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22296. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22297. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22298. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22299. this._rigCameras[0].parent = this;
  22300. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22301. //Right eye
  22302. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22303. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22304. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22305. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22306. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22307. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22308. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22309. this._rigCameras[1].parent = this;
  22310. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22311. if (Camera.UseAlternateWebVRRendering) {
  22312. this._rigCameras[1]._skipRendering = true;
  22313. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22314. }
  22315. }
  22316. break;
  22317. }
  22318. this._cascadePostProcessesToRigCams();
  22319. this.update();
  22320. };
  22321. Camera.prototype._getVRProjectionMatrix = function () {
  22322. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22323. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22324. return this._projectionMatrix;
  22325. };
  22326. Camera.prototype._updateCameraRotationMatrix = function () {
  22327. //Here for WebVR
  22328. };
  22329. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22330. //Here for WebVR
  22331. };
  22332. /**
  22333. * This function MUST be overwritten by the different WebVR cameras available.
  22334. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22335. */
  22336. Camera.prototype._getWebVRProjectionMatrix = function () {
  22337. return BABYLON.Matrix.Identity();
  22338. };
  22339. /**
  22340. * This function MUST be overwritten by the different WebVR cameras available.
  22341. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22342. */
  22343. Camera.prototype._getWebVRViewMatrix = function () {
  22344. return BABYLON.Matrix.Identity();
  22345. };
  22346. Camera.prototype.setCameraRigParameter = function (name, value) {
  22347. if (!this._cameraRigParams) {
  22348. this._cameraRigParams = {};
  22349. }
  22350. this._cameraRigParams[name] = value;
  22351. //provisionnally:
  22352. if (name === "interaxialDistance") {
  22353. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22354. }
  22355. };
  22356. /**
  22357. * needs to be overridden by children so sub has required properties to be copied
  22358. */
  22359. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22360. return null;
  22361. };
  22362. /**
  22363. * May need to be overridden by children
  22364. */
  22365. Camera.prototype._updateRigCameras = function () {
  22366. for (var i = 0; i < this._rigCameras.length; i++) {
  22367. this._rigCameras[i].minZ = this.minZ;
  22368. this._rigCameras[i].maxZ = this.maxZ;
  22369. this._rigCameras[i].fov = this.fov;
  22370. }
  22371. // only update viewport when ANAGLYPH
  22372. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22373. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22374. }
  22375. };
  22376. Camera.prototype._setupInputs = function () {
  22377. };
  22378. Camera.prototype.serialize = function () {
  22379. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22380. // Type
  22381. serializationObject.type = this.getClassName();
  22382. // Parent
  22383. if (this.parent) {
  22384. serializationObject.parentId = this.parent.id;
  22385. }
  22386. if (this.inputs) {
  22387. this.inputs.serialize(serializationObject);
  22388. }
  22389. // Animations
  22390. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22391. serializationObject.ranges = this.serializeAnimationRanges();
  22392. return serializationObject;
  22393. };
  22394. Camera.prototype.clone = function (name) {
  22395. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22396. };
  22397. Camera.prototype.getDirection = function (localAxis) {
  22398. var result = BABYLON.Vector3.Zero();
  22399. this.getDirectionToRef(localAxis, result);
  22400. return result;
  22401. };
  22402. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22403. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22404. };
  22405. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22406. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22407. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22408. switch (type) {
  22409. case "ArcRotateCamera":
  22410. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22411. case "DeviceOrientationCamera":
  22412. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22413. case "FollowCamera":
  22414. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22415. case "ArcFollowCamera":
  22416. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22417. case "GamepadCamera":
  22418. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22419. case "TouchCamera":
  22420. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22421. case "VirtualJoysticksCamera":
  22422. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22423. case "WebVRFreeCamera":
  22424. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22425. case "WebVRGamepadCamera":
  22426. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22427. case "VRDeviceOrientationFreeCamera":
  22428. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22429. case "VRDeviceOrientationGamepadCamera":
  22430. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22431. case "AnaglyphArcRotateCamera":
  22432. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22433. case "AnaglyphFreeCamera":
  22434. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22435. case "AnaglyphGamepadCamera":
  22436. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22437. case "AnaglyphUniversalCamera":
  22438. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22439. case "StereoscopicArcRotateCamera":
  22440. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22441. case "StereoscopicFreeCamera":
  22442. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22443. case "StereoscopicGamepadCamera":
  22444. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22445. case "StereoscopicUniversalCamera":
  22446. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22447. case "FreeCamera":// Forcing Universal here
  22448. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22449. default:// Universal Camera is the default value
  22450. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22451. }
  22452. };
  22453. Camera.prototype.computeWorldMatrix = function () {
  22454. return this.getWorldMatrix();
  22455. };
  22456. Camera.Parse = function (parsedCamera, scene) {
  22457. var type = parsedCamera.type;
  22458. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22459. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22460. // Parent
  22461. if (parsedCamera.parentId) {
  22462. camera._waitingParentId = parsedCamera.parentId;
  22463. }
  22464. //If camera has an input manager, let it parse inputs settings
  22465. if (camera.inputs) {
  22466. camera.inputs.parse(parsedCamera);
  22467. camera._setupInputs();
  22468. }
  22469. if (camera.setPosition) {
  22470. camera.position.copyFromFloats(0, 0, 0);
  22471. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22472. }
  22473. // Target
  22474. if (parsedCamera.target) {
  22475. if (camera.setTarget) {
  22476. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22477. }
  22478. }
  22479. // Apply 3d rig, when found
  22480. if (parsedCamera.cameraRigMode) {
  22481. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22482. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22483. }
  22484. // Animations
  22485. if (parsedCamera.animations) {
  22486. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22487. var parsedAnimation = parsedCamera.animations[animationIndex];
  22488. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22489. }
  22490. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22491. }
  22492. if (parsedCamera.autoAnimate) {
  22493. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22494. }
  22495. return camera;
  22496. };
  22497. // Statics
  22498. Camera._PERSPECTIVE_CAMERA = 0;
  22499. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22500. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22501. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22502. Camera._RIG_MODE_NONE = 0;
  22503. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22504. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22505. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22506. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22507. Camera._RIG_MODE_VR = 20;
  22508. Camera._RIG_MODE_WEBVR = 21;
  22509. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22510. Camera.UseAlternateWebVRRendering = false;
  22511. __decorate([
  22512. BABYLON.serializeAsVector3()
  22513. ], Camera.prototype, "position", void 0);
  22514. __decorate([
  22515. BABYLON.serializeAsVector3()
  22516. ], Camera.prototype, "upVector", void 0);
  22517. __decorate([
  22518. BABYLON.serialize()
  22519. ], Camera.prototype, "orthoLeft", void 0);
  22520. __decorate([
  22521. BABYLON.serialize()
  22522. ], Camera.prototype, "orthoRight", void 0);
  22523. __decorate([
  22524. BABYLON.serialize()
  22525. ], Camera.prototype, "orthoBottom", void 0);
  22526. __decorate([
  22527. BABYLON.serialize()
  22528. ], Camera.prototype, "orthoTop", void 0);
  22529. __decorate([
  22530. BABYLON.serialize()
  22531. ], Camera.prototype, "fov", void 0);
  22532. __decorate([
  22533. BABYLON.serialize()
  22534. ], Camera.prototype, "minZ", void 0);
  22535. __decorate([
  22536. BABYLON.serialize()
  22537. ], Camera.prototype, "maxZ", void 0);
  22538. __decorate([
  22539. BABYLON.serialize()
  22540. ], Camera.prototype, "inertia", void 0);
  22541. __decorate([
  22542. BABYLON.serialize()
  22543. ], Camera.prototype, "mode", void 0);
  22544. __decorate([
  22545. BABYLON.serialize()
  22546. ], Camera.prototype, "layerMask", void 0);
  22547. __decorate([
  22548. BABYLON.serialize()
  22549. ], Camera.prototype, "fovMode", void 0);
  22550. __decorate([
  22551. BABYLON.serialize()
  22552. ], Camera.prototype, "cameraRigMode", void 0);
  22553. __decorate([
  22554. BABYLON.serialize()
  22555. ], Camera.prototype, "interaxialDistance", void 0);
  22556. __decorate([
  22557. BABYLON.serialize()
  22558. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22559. return Camera;
  22560. }(BABYLON.Node));
  22561. BABYLON.Camera = Camera;
  22562. })(BABYLON || (BABYLON = {}));
  22563. //# sourceMappingURL=babylon.camera.js.map
  22564. "use strict";
  22565. var BABYLON;
  22566. (function (BABYLON) {
  22567. var RenderingManager = /** @class */ (function () {
  22568. function RenderingManager(scene) {
  22569. this._renderingGroups = new Array();
  22570. this._autoClearDepthStencil = {};
  22571. this._customOpaqueSortCompareFn = {};
  22572. this._customAlphaTestSortCompareFn = {};
  22573. this._customTransparentSortCompareFn = {};
  22574. this._renderinGroupInfo = null;
  22575. this._scene = scene;
  22576. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22577. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22578. }
  22579. }
  22580. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22581. if (depth === void 0) { depth = true; }
  22582. if (stencil === void 0) { stencil = true; }
  22583. if (this._depthStencilBufferAlreadyCleaned) {
  22584. return;
  22585. }
  22586. this._scene.getEngine().clear(null, false, depth, stencil);
  22587. this._depthStencilBufferAlreadyCleaned = true;
  22588. };
  22589. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22590. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22591. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22592. var info = null;
  22593. if (observable) {
  22594. if (!this._renderinGroupInfo) {
  22595. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22596. }
  22597. info = this._renderinGroupInfo;
  22598. info.scene = this._scene;
  22599. info.camera = this._scene.activeCamera;
  22600. }
  22601. // Dispatch sprites
  22602. if (renderSprites) {
  22603. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22604. var manager = this._scene.spriteManagers[index];
  22605. this.dispatchSprites(manager);
  22606. }
  22607. }
  22608. // Render
  22609. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22610. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22611. var renderingGroup = this._renderingGroups[index];
  22612. if (!renderingGroup && !observable)
  22613. continue;
  22614. var renderingGroupMask = 0;
  22615. // Fire PRECLEAR stage
  22616. if (observable && info) {
  22617. renderingGroupMask = Math.pow(2, index);
  22618. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22619. info.renderingGroupId = index;
  22620. observable.notifyObservers(info, renderingGroupMask);
  22621. }
  22622. // Clear depth/stencil if needed
  22623. if (RenderingManager.AUTOCLEAR) {
  22624. var autoClear = this._autoClearDepthStencil[index];
  22625. if (autoClear && autoClear.autoClear) {
  22626. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22627. }
  22628. }
  22629. if (observable && info) {
  22630. // Fire PREOPAQUE stage
  22631. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22632. observable.notifyObservers(info, renderingGroupMask);
  22633. // Fire PRETRANSPARENT stage
  22634. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22635. observable.notifyObservers(info, renderingGroupMask);
  22636. }
  22637. if (renderingGroup)
  22638. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22639. // Fire POSTTRANSPARENT stage
  22640. if (observable && info) {
  22641. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22642. observable.notifyObservers(info, renderingGroupMask);
  22643. }
  22644. }
  22645. };
  22646. RenderingManager.prototype.reset = function () {
  22647. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22648. var renderingGroup = this._renderingGroups[index];
  22649. if (renderingGroup) {
  22650. renderingGroup.prepare();
  22651. }
  22652. }
  22653. };
  22654. RenderingManager.prototype.dispose = function () {
  22655. this.freeRenderingGroups();
  22656. this._renderingGroups.length = 0;
  22657. };
  22658. /**
  22659. * Clear the info related to rendering groups preventing retention points during dispose.
  22660. */
  22661. RenderingManager.prototype.freeRenderingGroups = function () {
  22662. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22663. var renderingGroup = this._renderingGroups[index];
  22664. if (renderingGroup) {
  22665. renderingGroup.dispose();
  22666. }
  22667. }
  22668. };
  22669. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22670. if (this._renderingGroups[renderingGroupId] === undefined) {
  22671. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22672. }
  22673. };
  22674. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22675. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22676. this._prepareRenderingGroup(renderingGroupId);
  22677. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22678. };
  22679. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22680. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22681. this._prepareRenderingGroup(renderingGroupId);
  22682. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22683. };
  22684. /**
  22685. * @param subMesh The submesh to dispatch
  22686. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22687. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22688. */
  22689. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22690. if (mesh === undefined) {
  22691. mesh = subMesh.getMesh();
  22692. }
  22693. var renderingGroupId = mesh.renderingGroupId || 0;
  22694. this._prepareRenderingGroup(renderingGroupId);
  22695. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22696. };
  22697. /**
  22698. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22699. * This allowed control for front to back rendering or reversly depending of the special needs.
  22700. *
  22701. * @param renderingGroupId The rendering group id corresponding to its index
  22702. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22703. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22704. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22705. */
  22706. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22707. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22708. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22709. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22710. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22711. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22712. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22713. if (this._renderingGroups[renderingGroupId]) {
  22714. var group = this._renderingGroups[renderingGroupId];
  22715. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22716. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22717. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22718. }
  22719. };
  22720. /**
  22721. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22722. *
  22723. * @param renderingGroupId The rendering group id corresponding to its index
  22724. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22725. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22726. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22727. */
  22728. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22729. if (depth === void 0) { depth = true; }
  22730. if (stencil === void 0) { stencil = true; }
  22731. this._autoClearDepthStencil[renderingGroupId] = {
  22732. autoClear: autoClearDepthStencil,
  22733. depth: depth,
  22734. stencil: stencil
  22735. };
  22736. };
  22737. /**
  22738. * The max id used for rendering groups (not included)
  22739. */
  22740. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22741. /**
  22742. * The min id used for rendering groups (included)
  22743. */
  22744. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22745. /**
  22746. * Used to globally prevent autoclearing scenes.
  22747. */
  22748. RenderingManager.AUTOCLEAR = true;
  22749. return RenderingManager;
  22750. }());
  22751. BABYLON.RenderingManager = RenderingManager;
  22752. })(BABYLON || (BABYLON = {}));
  22753. //# sourceMappingURL=babylon.renderingManager.js.map
  22754. "use strict";
  22755. var BABYLON;
  22756. (function (BABYLON) {
  22757. var RenderingGroup = /** @class */ (function () {
  22758. /**
  22759. * Creates a new rendering group.
  22760. * @param index The rendering group index
  22761. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22762. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22763. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22764. */
  22765. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22766. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22767. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22768. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22769. this.index = index;
  22770. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22771. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22772. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22773. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22774. this._particleSystems = new BABYLON.SmartArray(256);
  22775. this._spriteManagers = new BABYLON.SmartArray(256);
  22776. this._edgesRenderers = new BABYLON.SmartArray(16);
  22777. this._scene = scene;
  22778. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22779. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22780. this.transparentSortCompareFn = transparentSortCompareFn;
  22781. }
  22782. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22783. /**
  22784. * Set the opaque sort comparison function.
  22785. * If null the sub meshes will be render in the order they were created
  22786. */
  22787. set: function (value) {
  22788. this._opaqueSortCompareFn = value;
  22789. if (value) {
  22790. this._renderOpaque = this.renderOpaqueSorted;
  22791. }
  22792. else {
  22793. this._renderOpaque = RenderingGroup.renderUnsorted;
  22794. }
  22795. },
  22796. enumerable: true,
  22797. configurable: true
  22798. });
  22799. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22800. /**
  22801. * Set the alpha test sort comparison function.
  22802. * If null the sub meshes will be render in the order they were created
  22803. */
  22804. set: function (value) {
  22805. this._alphaTestSortCompareFn = value;
  22806. if (value) {
  22807. this._renderAlphaTest = this.renderAlphaTestSorted;
  22808. }
  22809. else {
  22810. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22811. }
  22812. },
  22813. enumerable: true,
  22814. configurable: true
  22815. });
  22816. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22817. /**
  22818. * Set the transparent sort comparison function.
  22819. * If null the sub meshes will be render in the order they were created
  22820. */
  22821. set: function (value) {
  22822. if (value) {
  22823. this._transparentSortCompareFn = value;
  22824. }
  22825. else {
  22826. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22827. }
  22828. this._renderTransparent = this.renderTransparentSorted;
  22829. },
  22830. enumerable: true,
  22831. configurable: true
  22832. });
  22833. /**
  22834. * Render all the sub meshes contained in the group.
  22835. * @param customRenderFunction Used to override the default render behaviour of the group.
  22836. * @returns true if rendered some submeshes.
  22837. */
  22838. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22839. if (customRenderFunction) {
  22840. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22841. return;
  22842. }
  22843. var engine = this._scene.getEngine();
  22844. // Depth only
  22845. if (this._depthOnlySubMeshes.length !== 0) {
  22846. engine.setColorWrite(false);
  22847. this._renderAlphaTest(this._depthOnlySubMeshes);
  22848. engine.setColorWrite(true);
  22849. }
  22850. // Opaque
  22851. if (this._opaqueSubMeshes.length !== 0) {
  22852. this._renderOpaque(this._opaqueSubMeshes);
  22853. }
  22854. // Alpha test
  22855. if (this._alphaTestSubMeshes.length !== 0) {
  22856. this._renderAlphaTest(this._alphaTestSubMeshes);
  22857. }
  22858. var stencilState = engine.getStencilBuffer();
  22859. engine.setStencilBuffer(false);
  22860. // Sprites
  22861. if (renderSprites) {
  22862. this._renderSprites();
  22863. }
  22864. // Particles
  22865. if (renderParticles) {
  22866. this._renderParticles(activeMeshes);
  22867. }
  22868. if (this.onBeforeTransparentRendering) {
  22869. this.onBeforeTransparentRendering();
  22870. }
  22871. // Transparent
  22872. if (this._transparentSubMeshes.length !== 0) {
  22873. this._renderTransparent(this._transparentSubMeshes);
  22874. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22875. }
  22876. // Set back stencil to false in case it changes before the edge renderer.
  22877. engine.setStencilBuffer(false);
  22878. // Edges
  22879. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22880. this._edgesRenderers.data[edgesRendererIndex].render();
  22881. }
  22882. // Restore Stencil state.
  22883. engine.setStencilBuffer(stencilState);
  22884. };
  22885. /**
  22886. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22887. * @param subMeshes The submeshes to render
  22888. */
  22889. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22890. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22891. };
  22892. /**
  22893. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22894. * @param subMeshes The submeshes to render
  22895. */
  22896. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22897. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22898. };
  22899. /**
  22900. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22901. * @param subMeshes The submeshes to render
  22902. */
  22903. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22904. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22905. };
  22906. /**
  22907. * Renders the submeshes in a specified order.
  22908. * @param subMeshes The submeshes to sort before render
  22909. * @param sortCompareFn The comparison function use to sort
  22910. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22911. * @param transparent Specifies to activate blending if true
  22912. */
  22913. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22914. var subIndex = 0;
  22915. var subMesh;
  22916. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22917. for (; subIndex < subMeshes.length; subIndex++) {
  22918. subMesh = subMeshes.data[subIndex];
  22919. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22920. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22921. }
  22922. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22923. if (sortCompareFn) {
  22924. sortedArray.sort(sortCompareFn);
  22925. }
  22926. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22927. subMesh = sortedArray[subIndex];
  22928. if (transparent) {
  22929. var material = subMesh.getMaterial();
  22930. if (material && material.needDepthPrePass) {
  22931. var engine = material.getScene().getEngine();
  22932. engine.setColorWrite(false);
  22933. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22934. subMesh.render(false);
  22935. engine.setColorWrite(true);
  22936. }
  22937. }
  22938. subMesh.render(transparent);
  22939. }
  22940. };
  22941. /**
  22942. * Renders the submeshes in the order they were dispatched (no sort applied).
  22943. * @param subMeshes The submeshes to render
  22944. */
  22945. RenderingGroup.renderUnsorted = function (subMeshes) {
  22946. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22947. var submesh = subMeshes.data[subIndex];
  22948. submesh.render(false);
  22949. }
  22950. };
  22951. /**
  22952. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22953. * are rendered back to front if in the same alpha index.
  22954. *
  22955. * @param a The first submesh
  22956. * @param b The second submesh
  22957. * @returns The result of the comparison
  22958. */
  22959. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22960. // Alpha index first
  22961. if (a._alphaIndex > b._alphaIndex) {
  22962. return 1;
  22963. }
  22964. if (a._alphaIndex < b._alphaIndex) {
  22965. return -1;
  22966. }
  22967. // Then distance to camera
  22968. return RenderingGroup.backToFrontSortCompare(a, b);
  22969. };
  22970. /**
  22971. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22972. * are rendered back to front.
  22973. *
  22974. * @param a The first submesh
  22975. * @param b The second submesh
  22976. * @returns The result of the comparison
  22977. */
  22978. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22979. // Then distance to camera
  22980. if (a._distanceToCamera < b._distanceToCamera) {
  22981. return 1;
  22982. }
  22983. if (a._distanceToCamera > b._distanceToCamera) {
  22984. return -1;
  22985. }
  22986. return 0;
  22987. };
  22988. /**
  22989. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22990. * are rendered front to back (prevent overdraw).
  22991. *
  22992. * @param a The first submesh
  22993. * @param b The second submesh
  22994. * @returns The result of the comparison
  22995. */
  22996. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22997. // Then distance to camera
  22998. if (a._distanceToCamera < b._distanceToCamera) {
  22999. return -1;
  23000. }
  23001. if (a._distanceToCamera > b._distanceToCamera) {
  23002. return 1;
  23003. }
  23004. return 0;
  23005. };
  23006. /**
  23007. * Resets the different lists of submeshes to prepare a new frame.
  23008. */
  23009. RenderingGroup.prototype.prepare = function () {
  23010. this._opaqueSubMeshes.reset();
  23011. this._transparentSubMeshes.reset();
  23012. this._alphaTestSubMeshes.reset();
  23013. this._depthOnlySubMeshes.reset();
  23014. this._particleSystems.reset();
  23015. this._spriteManagers.reset();
  23016. this._edgesRenderers.reset();
  23017. };
  23018. RenderingGroup.prototype.dispose = function () {
  23019. this._opaqueSubMeshes.dispose();
  23020. this._transparentSubMeshes.dispose();
  23021. this._alphaTestSubMeshes.dispose();
  23022. this._depthOnlySubMeshes.dispose();
  23023. this._particleSystems.dispose();
  23024. this._spriteManagers.dispose();
  23025. this._edgesRenderers.dispose();
  23026. };
  23027. /**
  23028. * Inserts the submesh in its correct queue depending on its material.
  23029. * @param subMesh The submesh to dispatch
  23030. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23031. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23032. */
  23033. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23034. // Get mesh and materials if not provided
  23035. if (mesh === undefined) {
  23036. mesh = subMesh.getMesh();
  23037. }
  23038. if (material === undefined) {
  23039. material = subMesh.getMaterial();
  23040. }
  23041. if (material === null || material === undefined) {
  23042. return;
  23043. }
  23044. if (material.needAlphaBlendingForMesh(mesh)) {
  23045. this._transparentSubMeshes.push(subMesh);
  23046. }
  23047. else if (material.needAlphaTesting()) {
  23048. if (material.needDepthPrePass) {
  23049. this._depthOnlySubMeshes.push(subMesh);
  23050. }
  23051. this._alphaTestSubMeshes.push(subMesh);
  23052. }
  23053. else {
  23054. if (material.needDepthPrePass) {
  23055. this._depthOnlySubMeshes.push(subMesh);
  23056. }
  23057. this._opaqueSubMeshes.push(subMesh); // Opaque
  23058. }
  23059. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23060. this._edgesRenderers.push(mesh._edgesRenderer);
  23061. }
  23062. };
  23063. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23064. this._spriteManagers.push(spriteManager);
  23065. };
  23066. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23067. this._particleSystems.push(particleSystem);
  23068. };
  23069. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23070. if (this._particleSystems.length === 0) {
  23071. return;
  23072. }
  23073. // Particles
  23074. var activeCamera = this._scene.activeCamera;
  23075. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23076. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23077. var particleSystem = this._particleSystems.data[particleIndex];
  23078. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23079. continue;
  23080. }
  23081. var emitter = particleSystem.emitter;
  23082. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23083. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23084. }
  23085. }
  23086. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23087. };
  23088. RenderingGroup.prototype._renderSprites = function () {
  23089. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23090. return;
  23091. }
  23092. // Sprites
  23093. var activeCamera = this._scene.activeCamera;
  23094. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23095. for (var id = 0; id < this._spriteManagers.length; id++) {
  23096. var spriteManager = this._spriteManagers.data[id];
  23097. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23098. spriteManager.render();
  23099. }
  23100. }
  23101. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23102. };
  23103. return RenderingGroup;
  23104. }());
  23105. BABYLON.RenderingGroup = RenderingGroup;
  23106. })(BABYLON || (BABYLON = {}));
  23107. //# sourceMappingURL=babylon.renderingGroup.js.map
  23108. "use strict";
  23109. var BABYLON;
  23110. (function (BABYLON) {
  23111. /** @ignore */
  23112. var ClickInfo = /** @class */ (function () {
  23113. function ClickInfo() {
  23114. this._singleClick = false;
  23115. this._doubleClick = false;
  23116. this._hasSwiped = false;
  23117. this._ignore = false;
  23118. }
  23119. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23120. get: function () {
  23121. return this._singleClick;
  23122. },
  23123. set: function (b) {
  23124. this._singleClick = b;
  23125. },
  23126. enumerable: true,
  23127. configurable: true
  23128. });
  23129. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23130. get: function () {
  23131. return this._doubleClick;
  23132. },
  23133. set: function (b) {
  23134. this._doubleClick = b;
  23135. },
  23136. enumerable: true,
  23137. configurable: true
  23138. });
  23139. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23140. get: function () {
  23141. return this._hasSwiped;
  23142. },
  23143. set: function (b) {
  23144. this._hasSwiped = b;
  23145. },
  23146. enumerable: true,
  23147. configurable: true
  23148. });
  23149. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23150. get: function () {
  23151. return this._ignore;
  23152. },
  23153. set: function (b) {
  23154. this._ignore = b;
  23155. },
  23156. enumerable: true,
  23157. configurable: true
  23158. });
  23159. return ClickInfo;
  23160. }());
  23161. /**
  23162. * This class is used by the onRenderingGroupObservable
  23163. */
  23164. var RenderingGroupInfo = /** @class */ (function () {
  23165. function RenderingGroupInfo() {
  23166. }
  23167. /**
  23168. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23169. * This stage will be fired no matter what
  23170. */
  23171. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23172. /**
  23173. * Called before opaque object are rendered.
  23174. * This stage will be fired only if there's 3D Opaque content to render
  23175. */
  23176. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23177. /**
  23178. * Called after the opaque objects are rendered and before the transparent ones
  23179. * This stage will be fired only if there's 3D transparent content to render
  23180. */
  23181. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23182. /**
  23183. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23184. * This stage will be fired no matter what
  23185. */
  23186. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23187. return RenderingGroupInfo;
  23188. }());
  23189. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23190. /**
  23191. * Represents a scene to be rendered by the engine.
  23192. * @see http://doc.babylonjs.com/features/scene
  23193. */
  23194. var Scene = /** @class */ (function () {
  23195. /**
  23196. * Creates a new Scene
  23197. * @param engine defines the engine to use to render this scene
  23198. */
  23199. function Scene(engine) {
  23200. // Members
  23201. /**
  23202. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23203. */
  23204. this.autoClear = true;
  23205. /**
  23206. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23207. */
  23208. this.autoClearDepthAndStencil = true;
  23209. /**
  23210. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23211. */
  23212. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23213. /**
  23214. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23215. */
  23216. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23217. this._forceWireframe = false;
  23218. this._forcePointsCloud = false;
  23219. /**
  23220. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23221. */
  23222. this.forceShowBoundingBoxes = false;
  23223. /**
  23224. * Gets or sets a boolean indicating if animations are enabled
  23225. */
  23226. this.animationsEnabled = true;
  23227. /**
  23228. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23229. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23230. */
  23231. this.useConstantAnimationDeltaTime = false;
  23232. /**
  23233. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23234. * Please note that it requires to run a ray cast through the scene on every frame
  23235. */
  23236. this.constantlyUpdateMeshUnderPointer = false;
  23237. /**
  23238. * Defines the HTML cursor to use when hovering over interactive elements
  23239. */
  23240. this.hoverCursor = "pointer";
  23241. /**
  23242. * Defines the HTML default cursor to use (empty by default)
  23243. */
  23244. this.defaultCursor = "";
  23245. /**
  23246. * This is used to call preventDefault() on pointer down
  23247. * in order to block unwanted artifacts like system double clicks
  23248. */
  23249. this.preventDefaultOnPointerDown = true;
  23250. // Metadata
  23251. /**
  23252. * Gets or sets user defined metadata
  23253. */
  23254. this.metadata = null;
  23255. /**
  23256. * Use this array to add regular expressions used to disable offline support for specific urls
  23257. */
  23258. this.disableOfflineSupportExceptionRules = new Array();
  23259. /**
  23260. * An event triggered when the scene is disposed.
  23261. */
  23262. this.onDisposeObservable = new BABYLON.Observable();
  23263. this._onDisposeObserver = null;
  23264. /**
  23265. * An event triggered before rendering the scene (right after animations and physics)
  23266. */
  23267. this.onBeforeRenderObservable = new BABYLON.Observable();
  23268. this._onBeforeRenderObserver = null;
  23269. /**
  23270. * An event triggered after rendering the scene
  23271. */
  23272. this.onAfterRenderObservable = new BABYLON.Observable();
  23273. this._onAfterRenderObserver = null;
  23274. /**
  23275. * An event triggered before animating the scene
  23276. */
  23277. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23278. /**
  23279. * An event triggered after animations processing
  23280. */
  23281. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23282. /**
  23283. * An event triggered before draw calls are ready to be sent
  23284. */
  23285. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23286. /**
  23287. * An event triggered after draw calls have been sent
  23288. */
  23289. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23290. /**
  23291. * An event triggered when physic simulation is about to be run
  23292. */
  23293. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23294. /**
  23295. * An event triggered when physic simulation has been done
  23296. */
  23297. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23298. /**
  23299. * An event triggered when the scene is ready
  23300. */
  23301. this.onReadyObservable = new BABYLON.Observable();
  23302. /**
  23303. * An event triggered before rendering a camera
  23304. */
  23305. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23306. this._onBeforeCameraRenderObserver = null;
  23307. /**
  23308. * An event triggered after rendering a camera
  23309. */
  23310. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23311. this._onAfterCameraRenderObserver = null;
  23312. /**
  23313. * An event triggered when active meshes evaluation is about to start
  23314. */
  23315. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23316. /**
  23317. * An event triggered when active meshes evaluation is done
  23318. */
  23319. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23320. /**
  23321. * An event triggered when particles rendering is about to start
  23322. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23323. */
  23324. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23325. /**
  23326. * An event triggered when particles rendering is done
  23327. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23328. */
  23329. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23330. /**
  23331. * An event triggered when sprites rendering is about to start
  23332. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23333. */
  23334. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23335. /**
  23336. * An event triggered when sprites rendering is done
  23337. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23338. */
  23339. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23340. /**
  23341. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23342. */
  23343. this.onDataLoadedObservable = new BABYLON.Observable();
  23344. /**
  23345. * An event triggered when a camera is created
  23346. */
  23347. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23348. /**
  23349. * An event triggered when a camera is removed
  23350. */
  23351. this.onCameraRemovedObservable = new BABYLON.Observable();
  23352. /**
  23353. * An event triggered when a light is created
  23354. */
  23355. this.onNewLightAddedObservable = new BABYLON.Observable();
  23356. /**
  23357. * An event triggered when a light is removed
  23358. */
  23359. this.onLightRemovedObservable = new BABYLON.Observable();
  23360. /**
  23361. * An event triggered when a geometry is created
  23362. */
  23363. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23364. /**
  23365. * An event triggered when a geometry is removed
  23366. */
  23367. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23368. /**
  23369. * An event triggered when a transform node is created
  23370. */
  23371. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23372. /**
  23373. * An event triggered when a transform node is removed
  23374. */
  23375. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23376. /**
  23377. * An event triggered when a mesh is created
  23378. */
  23379. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23380. /**
  23381. * An event triggered when a mesh is removed
  23382. */
  23383. this.onMeshRemovedObservable = new BABYLON.Observable();
  23384. /**
  23385. * An event triggered when render targets are about to be rendered
  23386. * Can happen multiple times per frame.
  23387. */
  23388. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23389. /**
  23390. * An event triggered when render targets were rendered.
  23391. * Can happen multiple times per frame.
  23392. */
  23393. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23394. /**
  23395. * An event triggered before calculating deterministic simulation step
  23396. */
  23397. this.onBeforeStepObservable = new BABYLON.Observable();
  23398. /**
  23399. * An event triggered after calculating deterministic simulation step
  23400. */
  23401. this.onAfterStepObservable = new BABYLON.Observable();
  23402. /**
  23403. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23404. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23405. * 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)
  23406. */
  23407. this.onRenderingGroupObservable = new BABYLON.Observable();
  23408. // Animations
  23409. /**
  23410. * Gets a list of Animations associated with the scene
  23411. */
  23412. this.animations = [];
  23413. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23414. /**
  23415. * 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).
  23416. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23417. */
  23418. this.onPrePointerObservable = new BABYLON.Observable();
  23419. /**
  23420. * Observable event triggered each time an input event is received from the rendering canvas
  23421. */
  23422. this.onPointerObservable = new BABYLON.Observable();
  23423. this._meshPickProceed = false;
  23424. this._currentPickResult = null;
  23425. this._previousPickResult = null;
  23426. this._totalPointersPressed = 0;
  23427. this._doubleClickOccured = false;
  23428. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23429. this.cameraToUseForPointers = null;
  23430. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23431. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23432. this._startingPointerTime = 0;
  23433. this._previousStartingPointerTime = 0;
  23434. // Deterministic lockstep
  23435. this._timeAccumulator = 0;
  23436. this._currentStepId = 0;
  23437. this._currentInternalStep = 0;
  23438. // Keyboard
  23439. /**
  23440. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23441. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23442. */
  23443. this.onPreKeyboardObservable = new BABYLON.Observable();
  23444. /**
  23445. * Observable event triggered each time an keyboard event is received from the hosting window
  23446. */
  23447. this.onKeyboardObservable = new BABYLON.Observable();
  23448. // Coordinates system
  23449. this._useRightHandedSystem = false;
  23450. // Fog
  23451. this._fogEnabled = true;
  23452. this._fogMode = Scene.FOGMODE_NONE;
  23453. /**
  23454. * Gets or sets the fog color to use
  23455. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23456. */
  23457. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23458. /**
  23459. * Gets or sets the fog density to use
  23460. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23461. */
  23462. this.fogDensity = 0.1;
  23463. /**
  23464. * Gets or sets the fog start distance to use
  23465. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23466. */
  23467. this.fogStart = 0;
  23468. /**
  23469. * Gets or sets the fog end distance to use
  23470. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23471. */
  23472. this.fogEnd = 1000.0;
  23473. // Lights
  23474. this._shadowsEnabled = true;
  23475. this._lightsEnabled = true;
  23476. /**
  23477. * All of the lights added to this scene
  23478. * @see http://doc.babylonjs.com/babylon101/lights
  23479. */
  23480. this.lights = new Array();
  23481. // Cameras
  23482. /** All of the cameras added to this scene.
  23483. * @see http://doc.babylonjs.com/babylon101/cameras
  23484. */
  23485. this.cameras = new Array();
  23486. /** All of the active cameras added to this scene. */
  23487. this.activeCameras = new Array();
  23488. // Meshes
  23489. /**
  23490. * All of the tranform nodes added to this scene
  23491. * @see http://doc.babylonjs.com/how_to/transformnode
  23492. */
  23493. this.transformNodes = new Array();
  23494. /**
  23495. * All of the (abstract) meshes added to this scene
  23496. */
  23497. this.meshes = new Array();
  23498. /**
  23499. * All of the animation groups added to this scene
  23500. * @see http://doc.babylonjs.com/how_to/group
  23501. */
  23502. this.animationGroups = new Array();
  23503. // Geometries
  23504. this._geometries = new Array();
  23505. /**
  23506. * All of the materials added to this scene
  23507. * @see http://doc.babylonjs.com/babylon101/materials
  23508. */
  23509. this.materials = new Array();
  23510. /**
  23511. * All of the multi-materials added to this scene
  23512. * @see http://doc.babylonjs.com/how_to/multi_materials
  23513. */
  23514. this.multiMaterials = new Array();
  23515. // Textures
  23516. this._texturesEnabled = true;
  23517. /**
  23518. * All of the textures added to this scene
  23519. */
  23520. this.textures = new Array();
  23521. // Particles
  23522. /**
  23523. * Gets or sets a boolean indicating if particles are enabled on this scene
  23524. */
  23525. this.particlesEnabled = true;
  23526. /**
  23527. * All of the particle systems added to this scene
  23528. * @see http://doc.babylonjs.com/babylon101/particles
  23529. */
  23530. this.particleSystems = new Array();
  23531. // Sprites
  23532. /**
  23533. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23534. */
  23535. this.spritesEnabled = true;
  23536. /**
  23537. * All of the sprite managers added to this scene
  23538. * @see http://doc.babylonjs.com/babylon101/sprites
  23539. */
  23540. this.spriteManagers = new Array();
  23541. /**
  23542. * The list of layers (background and foreground) of the scene
  23543. */
  23544. this.layers = new Array();
  23545. /**
  23546. * The list of effect layers (highlights/glow) added to the scene
  23547. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23548. * @see http://doc.babylonjs.com/how_to/glow_layer
  23549. */
  23550. this.effectLayers = new Array();
  23551. // Skeletons
  23552. this._skeletonsEnabled = true;
  23553. /**
  23554. * The list of skeletons added to the scene
  23555. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23556. */
  23557. this.skeletons = new Array();
  23558. // Morph targets
  23559. /**
  23560. * The list of morph target managers added to the scene
  23561. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23562. */
  23563. this.morphTargetManagers = new Array();
  23564. // Lens flares
  23565. /**
  23566. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23567. */
  23568. this.lensFlaresEnabled = true;
  23569. /**
  23570. * The list of lens flare system added to the scene
  23571. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23572. */
  23573. this.lensFlareSystems = new Array();
  23574. // Collisions
  23575. /**
  23576. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23577. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23578. */
  23579. this.collisionsEnabled = true;
  23580. /**
  23581. * Defines the gravity applied to this scene (used only for collisions)
  23582. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23583. */
  23584. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23585. // Postprocesses
  23586. /**
  23587. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23588. */
  23589. this.postProcessesEnabled = true;
  23590. /**
  23591. * The list of postprocesses added to the scene
  23592. */
  23593. this.postProcesses = new Array();
  23594. // Customs render targets
  23595. /**
  23596. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23597. */
  23598. this.renderTargetsEnabled = true;
  23599. /**
  23600. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23601. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23602. */
  23603. this.dumpNextRenderTargets = false;
  23604. /**
  23605. * The list of user defined render targets added to the scene
  23606. */
  23607. this.customRenderTargets = new Array();
  23608. /**
  23609. * Gets the list of meshes imported to the scene through SceneLoader
  23610. */
  23611. this.importedMeshesFiles = new Array();
  23612. // Probes
  23613. /**
  23614. * Gets or sets a boolean indicating if probes are enabled on this scene
  23615. */
  23616. this.probesEnabled = true;
  23617. /**
  23618. * The list of reflection probes added to the scene
  23619. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23620. */
  23621. this.reflectionProbes = new Array();
  23622. /** @ignore */
  23623. this._actionManagers = new Array();
  23624. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23625. // Procedural textures
  23626. /**
  23627. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23628. */
  23629. this.proceduralTexturesEnabled = true;
  23630. /**
  23631. * The list of procedural textures added to the scene
  23632. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23633. */
  23634. this.proceduralTextures = new Array();
  23635. /**
  23636. * The list of sound tracks added to the scene
  23637. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23638. */
  23639. this.soundTracks = new Array();
  23640. this._audioEnabled = true;
  23641. this._headphone = false;
  23642. // Performance counters
  23643. this._totalVertices = new BABYLON.PerfCounter();
  23644. /** @ignore */
  23645. this._activeIndices = new BABYLON.PerfCounter();
  23646. /** @ignore */
  23647. this._activeParticles = new BABYLON.PerfCounter();
  23648. /** @ignore */
  23649. this._activeBones = new BABYLON.PerfCounter();
  23650. this._animationTime = 0;
  23651. /**
  23652. * Gets or sets a general scale for animation speed
  23653. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23654. */
  23655. this.animationTimeScale = 1;
  23656. this._renderId = 0;
  23657. this._executeWhenReadyTimeoutId = -1;
  23658. this._intermediateRendering = false;
  23659. this._viewUpdateFlag = -1;
  23660. this._projectionUpdateFlag = -1;
  23661. this._alternateViewUpdateFlag = -1;
  23662. this._alternateProjectionUpdateFlag = -1;
  23663. /** @ignore */
  23664. this._toBeDisposed = new BABYLON.SmartArray(256);
  23665. this._activeRequests = new Array();
  23666. this._pendingData = new Array();
  23667. this._isDisposed = false;
  23668. /**
  23669. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23670. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23671. */
  23672. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23673. this._activeMeshes = new BABYLON.SmartArray(256);
  23674. this._processedMaterials = new BABYLON.SmartArray(256);
  23675. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23676. /** @ignore */
  23677. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23678. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23679. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23680. /** @ignore */
  23681. this._activeAnimatables = new Array();
  23682. this._transformMatrix = BABYLON.Matrix.Zero();
  23683. this._useAlternateCameraConfiguration = false;
  23684. this._alternateRendering = false;
  23685. /**
  23686. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23687. * This is useful if there are more lights that the maximum simulteanous authorized
  23688. */
  23689. this.requireLightSorting = false;
  23690. this._depthRenderer = {};
  23691. this._activeMeshesFrozen = false;
  23692. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23693. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23694. this._engine.scenes.push(this);
  23695. this._uid = null;
  23696. this._renderingManager = new BABYLON.RenderingManager(this);
  23697. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23698. if (BABYLON.OutlineRenderer) {
  23699. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23700. }
  23701. if (BABYLON.Tools.IsWindowObjectExist()) {
  23702. this.attachControl();
  23703. }
  23704. //simplification queue
  23705. if (BABYLON.SimplificationQueue) {
  23706. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23707. }
  23708. //collision coordinator initialization. For now legacy per default.
  23709. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23710. // Uniform Buffer
  23711. this._createUbo();
  23712. // Default Image processing definition.
  23713. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23714. }
  23715. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23716. /** The fog is deactivated */
  23717. get: function () {
  23718. return Scene._FOGMODE_NONE;
  23719. },
  23720. enumerable: true,
  23721. configurable: true
  23722. });
  23723. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23724. /** The fog density is following an exponential function */
  23725. get: function () {
  23726. return Scene._FOGMODE_EXP;
  23727. },
  23728. enumerable: true,
  23729. configurable: true
  23730. });
  23731. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23732. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23733. get: function () {
  23734. return Scene._FOGMODE_EXP2;
  23735. },
  23736. enumerable: true,
  23737. configurable: true
  23738. });
  23739. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23740. /** The fog density is following a linear function. */
  23741. get: function () {
  23742. return Scene._FOGMODE_LINEAR;
  23743. },
  23744. enumerable: true,
  23745. configurable: true
  23746. });
  23747. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23748. /**
  23749. * Texture used in all pbr material as the reflection texture.
  23750. * As in the majority of the scene they are the same (exception for multi room and so on),
  23751. * this is easier to reference from here than from all the materials.
  23752. */
  23753. get: function () {
  23754. return this._environmentTexture;
  23755. },
  23756. /**
  23757. * Texture used in all pbr material as the reflection texture.
  23758. * As in the majority of the scene they are the same (exception for multi room and so on),
  23759. * this is easier to set here than in all the materials.
  23760. */
  23761. set: function (value) {
  23762. if (this._environmentTexture === value) {
  23763. return;
  23764. }
  23765. this._environmentTexture = value;
  23766. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23767. },
  23768. enumerable: true,
  23769. configurable: true
  23770. });
  23771. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23772. /**
  23773. * Default image processing configuration used either in the rendering
  23774. * Forward main pass or through the imageProcessingPostProcess if present.
  23775. * As in the majority of the scene they are the same (exception for multi camera),
  23776. * this is easier to reference from here than from all the materials and post process.
  23777. *
  23778. * No setter as we it is a shared configuration, you can set the values instead.
  23779. */
  23780. get: function () {
  23781. return this._imageProcessingConfiguration;
  23782. },
  23783. enumerable: true,
  23784. configurable: true
  23785. });
  23786. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23787. get: function () {
  23788. return this._forceWireframe;
  23789. },
  23790. /**
  23791. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23792. */
  23793. set: function (value) {
  23794. if (this._forceWireframe === value) {
  23795. return;
  23796. }
  23797. this._forceWireframe = value;
  23798. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23799. },
  23800. enumerable: true,
  23801. configurable: true
  23802. });
  23803. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23804. get: function () {
  23805. return this._forcePointsCloud;
  23806. },
  23807. /**
  23808. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23809. */
  23810. set: function (value) {
  23811. if (this._forcePointsCloud === value) {
  23812. return;
  23813. }
  23814. this._forcePointsCloud = value;
  23815. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23816. },
  23817. enumerable: true,
  23818. configurable: true
  23819. });
  23820. Object.defineProperty(Scene.prototype, "onDispose", {
  23821. /** Sets a function to be executed when this scene is disposed. */
  23822. set: function (callback) {
  23823. if (this._onDisposeObserver) {
  23824. this.onDisposeObservable.remove(this._onDisposeObserver);
  23825. }
  23826. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23827. },
  23828. enumerable: true,
  23829. configurable: true
  23830. });
  23831. Object.defineProperty(Scene.prototype, "beforeRender", {
  23832. /** Sets a function to be executed before rendering this scene */
  23833. set: function (callback) {
  23834. if (this._onBeforeRenderObserver) {
  23835. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23836. }
  23837. if (callback) {
  23838. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23839. }
  23840. },
  23841. enumerable: true,
  23842. configurable: true
  23843. });
  23844. Object.defineProperty(Scene.prototype, "afterRender", {
  23845. /** Sets a function to be executed after rendering this scene */
  23846. set: function (callback) {
  23847. if (this._onAfterRenderObserver) {
  23848. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23849. }
  23850. if (callback) {
  23851. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23852. }
  23853. },
  23854. enumerable: true,
  23855. configurable: true
  23856. });
  23857. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23858. /** Sets a function to be executed before rendering a camera*/
  23859. set: function (callback) {
  23860. if (this._onBeforeCameraRenderObserver) {
  23861. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23862. }
  23863. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23869. /** Sets a function to be executed after rendering a camera*/
  23870. set: function (callback) {
  23871. if (this._onAfterCameraRenderObserver) {
  23872. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23873. }
  23874. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23875. },
  23876. enumerable: true,
  23877. configurable: true
  23878. });
  23879. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23880. /**
  23881. * Gets the gamepad manager associated with the scene
  23882. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23883. */
  23884. get: function () {
  23885. if (!this._gamepadManager) {
  23886. this._gamepadManager = new BABYLON.GamepadManager(this);
  23887. }
  23888. return this._gamepadManager;
  23889. },
  23890. enumerable: true,
  23891. configurable: true
  23892. });
  23893. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23894. /**
  23895. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23896. */
  23897. get: function () {
  23898. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23904. get: function () {
  23905. return this._useRightHandedSystem;
  23906. },
  23907. /**
  23908. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23909. */
  23910. set: function (value) {
  23911. if (this._useRightHandedSystem === value) {
  23912. return;
  23913. }
  23914. this._useRightHandedSystem = value;
  23915. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23916. },
  23917. enumerable: true,
  23918. configurable: true
  23919. });
  23920. /**
  23921. * Sets the step Id used by deterministic lock step
  23922. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23923. * @param newStepId defines the step Id
  23924. */
  23925. Scene.prototype.setStepId = function (newStepId) {
  23926. this._currentStepId = newStepId;
  23927. };
  23928. ;
  23929. /**
  23930. * Gets the step Id used by deterministic lock step
  23931. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23932. * @returns the step Id
  23933. */
  23934. Scene.prototype.getStepId = function () {
  23935. return this._currentStepId;
  23936. };
  23937. ;
  23938. /**
  23939. * Gets the internal step used by deterministic lock step
  23940. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23941. * @returns the internal step
  23942. */
  23943. Scene.prototype.getInternalStep = function () {
  23944. return this._currentInternalStep;
  23945. };
  23946. ;
  23947. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23948. get: function () {
  23949. return this._fogEnabled;
  23950. },
  23951. /**
  23952. * Gets or sets a boolean indicating if fog is enabled on this scene
  23953. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23954. */
  23955. set: function (value) {
  23956. if (this._fogEnabled === value) {
  23957. return;
  23958. }
  23959. this._fogEnabled = value;
  23960. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23961. },
  23962. enumerable: true,
  23963. configurable: true
  23964. });
  23965. Object.defineProperty(Scene.prototype, "fogMode", {
  23966. get: function () {
  23967. return this._fogMode;
  23968. },
  23969. /**
  23970. * Gets or sets the fog mode to use
  23971. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23972. */
  23973. set: function (value) {
  23974. if (this._fogMode === value) {
  23975. return;
  23976. }
  23977. this._fogMode = value;
  23978. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23984. get: function () {
  23985. return this._shadowsEnabled;
  23986. },
  23987. /**
  23988. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23989. */
  23990. set: function (value) {
  23991. if (this._shadowsEnabled === value) {
  23992. return;
  23993. }
  23994. this._shadowsEnabled = value;
  23995. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23996. },
  23997. enumerable: true,
  23998. configurable: true
  23999. });
  24000. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24001. get: function () {
  24002. return this._lightsEnabled;
  24003. },
  24004. /**
  24005. * Gets or sets a boolean indicating if lights are enabled on this scene
  24006. */
  24007. set: function (value) {
  24008. if (this._lightsEnabled === value) {
  24009. return;
  24010. }
  24011. this._lightsEnabled = value;
  24012. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24013. },
  24014. enumerable: true,
  24015. configurable: true
  24016. });
  24017. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24018. /** The default material used on meshes when no material is affected */
  24019. get: function () {
  24020. if (!this._defaultMaterial) {
  24021. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24022. }
  24023. return this._defaultMaterial;
  24024. },
  24025. /** The default material used on meshes when no material is affected */
  24026. set: function (value) {
  24027. this._defaultMaterial = value;
  24028. },
  24029. enumerable: true,
  24030. configurable: true
  24031. });
  24032. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24033. get: function () {
  24034. return this._texturesEnabled;
  24035. },
  24036. /**
  24037. * Gets or sets a boolean indicating if textures are enabled on this scene
  24038. */
  24039. set: function (value) {
  24040. if (this._texturesEnabled === value) {
  24041. return;
  24042. }
  24043. this._texturesEnabled = value;
  24044. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24050. get: function () {
  24051. return this._skeletonsEnabled;
  24052. },
  24053. /**
  24054. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24055. */
  24056. set: function (value) {
  24057. if (this._skeletonsEnabled === value) {
  24058. return;
  24059. }
  24060. this._skeletonsEnabled = value;
  24061. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24062. },
  24063. enumerable: true,
  24064. configurable: true
  24065. });
  24066. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24067. /**
  24068. * Gets the postprocess render pipeline manager
  24069. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24070. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24071. */
  24072. get: function () {
  24073. if (!this._postProcessRenderPipelineManager) {
  24074. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24075. }
  24076. return this._postProcessRenderPipelineManager;
  24077. },
  24078. enumerable: true,
  24079. configurable: true
  24080. });
  24081. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24082. /**
  24083. * Gets the main soundtrack associated with the scene
  24084. */
  24085. get: function () {
  24086. if (!this._mainSoundTrack) {
  24087. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24088. }
  24089. return this._mainSoundTrack;
  24090. },
  24091. enumerable: true,
  24092. configurable: true
  24093. });
  24094. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24095. /** @ignore */
  24096. get: function () {
  24097. return this._alternateRendering;
  24098. },
  24099. enumerable: true,
  24100. configurable: true
  24101. });
  24102. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24103. /**
  24104. * Gets the list of frustum planes (built from the active camera)
  24105. */
  24106. get: function () {
  24107. return this._frustumPlanes;
  24108. },
  24109. enumerable: true,
  24110. configurable: true
  24111. });
  24112. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24113. /**
  24114. * Gets the current geometry buffer associated to the scene.
  24115. */
  24116. get: function () {
  24117. return this._geometryBufferRenderer;
  24118. },
  24119. /**
  24120. * Sets the current geometry buffer for the scene.
  24121. */
  24122. set: function (geometryBufferRenderer) {
  24123. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24124. this._geometryBufferRenderer = geometryBufferRenderer;
  24125. }
  24126. },
  24127. enumerable: true,
  24128. configurable: true
  24129. });
  24130. Object.defineProperty(Scene.prototype, "debugLayer", {
  24131. /**
  24132. * Gets the debug layer associated with the scene
  24133. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24134. */
  24135. get: function () {
  24136. if (!this._debugLayer) {
  24137. this._debugLayer = new BABYLON.DebugLayer(this);
  24138. }
  24139. return this._debugLayer;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24145. /**
  24146. * Gets a boolean indicating if collisions are processed on a web worker
  24147. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24148. */
  24149. get: function () {
  24150. return this._workerCollisions;
  24151. },
  24152. set: function (enabled) {
  24153. if (!BABYLON.CollisionCoordinatorLegacy) {
  24154. return;
  24155. }
  24156. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24157. this._workerCollisions = enabled;
  24158. if (this.collisionCoordinator) {
  24159. this.collisionCoordinator.destroy();
  24160. }
  24161. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24162. this.collisionCoordinator.init(this);
  24163. },
  24164. enumerable: true,
  24165. configurable: true
  24166. });
  24167. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24168. /**
  24169. * Gets the octree used to boost mesh selection (picking)
  24170. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24171. */
  24172. get: function () {
  24173. return this._selectionOctree;
  24174. },
  24175. enumerable: true,
  24176. configurable: true
  24177. });
  24178. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24179. /**
  24180. * Gets the mesh that is currently under the pointer
  24181. */
  24182. get: function () {
  24183. return this._pointerOverMesh;
  24184. },
  24185. enumerable: true,
  24186. configurable: true
  24187. });
  24188. Object.defineProperty(Scene.prototype, "pointerX", {
  24189. /**
  24190. * Gets the current on-screen X position of the pointer
  24191. */
  24192. get: function () {
  24193. return this._pointerX;
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(Scene.prototype, "pointerY", {
  24199. /**
  24200. * Gets the current on-screen Y position of the pointer
  24201. */
  24202. get: function () {
  24203. return this._pointerY;
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. /**
  24209. * Gets the cached material (ie. the latest rendered one)
  24210. * @returns the cached material
  24211. */
  24212. Scene.prototype.getCachedMaterial = function () {
  24213. return this._cachedMaterial;
  24214. };
  24215. /**
  24216. * Gets the cached effect (ie. the latest rendered one)
  24217. * @returns the cached effect
  24218. */
  24219. Scene.prototype.getCachedEffect = function () {
  24220. return this._cachedEffect;
  24221. };
  24222. /**
  24223. * Gets the cached visibility state (ie. the latest rendered one)
  24224. * @returns the cached visibility state
  24225. */
  24226. Scene.prototype.getCachedVisibility = function () {
  24227. return this._cachedVisibility;
  24228. };
  24229. /**
  24230. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24231. * @param material defines the current material
  24232. * @param effect defines the current effect
  24233. * @param visibility defines the current visibility state
  24234. * @returns true if one parameter is not cached
  24235. */
  24236. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24237. if (visibility === void 0) { visibility = 1; }
  24238. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24239. };
  24240. /**
  24241. * Gets the bounding box renderer associated with the scene
  24242. * @returns a BoundingBoxRenderer
  24243. */
  24244. Scene.prototype.getBoundingBoxRenderer = function () {
  24245. if (!this._boundingBoxRenderer) {
  24246. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24247. }
  24248. return this._boundingBoxRenderer;
  24249. };
  24250. /**
  24251. * Gets the outline renderer associated with the scene
  24252. * @returns a OutlineRenderer
  24253. */
  24254. Scene.prototype.getOutlineRenderer = function () {
  24255. return this._outlineRenderer;
  24256. };
  24257. /**
  24258. * Gets the engine associated with the scene
  24259. * @returns an Engine
  24260. */
  24261. Scene.prototype.getEngine = function () {
  24262. return this._engine;
  24263. };
  24264. /**
  24265. * Gets the total number of vertices rendered per frame
  24266. * @returns the total number of vertices rendered per frame
  24267. */
  24268. Scene.prototype.getTotalVertices = function () {
  24269. return this._totalVertices.current;
  24270. };
  24271. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24272. /**
  24273. * Gets the performance counter for total vertices
  24274. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24275. */
  24276. get: function () {
  24277. return this._totalVertices;
  24278. },
  24279. enumerable: true,
  24280. configurable: true
  24281. });
  24282. /**
  24283. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24284. * @returns the total number of active indices rendered per frame
  24285. */
  24286. Scene.prototype.getActiveIndices = function () {
  24287. return this._activeIndices.current;
  24288. };
  24289. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24290. /**
  24291. * Gets the performance counter for active indices
  24292. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24293. */
  24294. get: function () {
  24295. return this._activeIndices;
  24296. },
  24297. enumerable: true,
  24298. configurable: true
  24299. });
  24300. /**
  24301. * Gets the total number of active particles rendered per frame
  24302. * @returns the total number of active particles rendered per frame
  24303. */
  24304. Scene.prototype.getActiveParticles = function () {
  24305. return this._activeParticles.current;
  24306. };
  24307. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24308. /**
  24309. * Gets the performance counter for active particles
  24310. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24311. */
  24312. get: function () {
  24313. return this._activeParticles;
  24314. },
  24315. enumerable: true,
  24316. configurable: true
  24317. });
  24318. /**
  24319. * Gets the total number of active bones rendered per frame
  24320. * @returns the total number of active bones rendered per frame
  24321. */
  24322. Scene.prototype.getActiveBones = function () {
  24323. return this._activeBones.current;
  24324. };
  24325. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24326. /**
  24327. * Gets the performance counter for active bones
  24328. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24329. */
  24330. get: function () {
  24331. return this._activeBones;
  24332. },
  24333. enumerable: true,
  24334. configurable: true
  24335. });
  24336. /** @ignore */
  24337. Scene.prototype.getInterFramePerfCounter = function () {
  24338. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24339. return 0;
  24340. };
  24341. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24342. /** @ignore */
  24343. get: function () {
  24344. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24345. return null;
  24346. },
  24347. enumerable: true,
  24348. configurable: true
  24349. });
  24350. /** @ignore */
  24351. Scene.prototype.getLastFrameDuration = function () {
  24352. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24353. return 0;
  24354. };
  24355. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24356. /** @ignore */
  24357. get: function () {
  24358. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24359. return null;
  24360. },
  24361. enumerable: true,
  24362. configurable: true
  24363. });
  24364. /** @ignore */
  24365. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24366. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24367. return 0;
  24368. };
  24369. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24370. /** @ignore */
  24371. get: function () {
  24372. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24373. return null;
  24374. },
  24375. enumerable: true,
  24376. configurable: true
  24377. });
  24378. /**
  24379. * Gets the array of active meshes
  24380. * @returns an array of AbstractMesh
  24381. */
  24382. Scene.prototype.getActiveMeshes = function () {
  24383. return this._activeMeshes;
  24384. };
  24385. /** @ignore */
  24386. Scene.prototype.getRenderTargetsDuration = function () {
  24387. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24388. return 0;
  24389. };
  24390. /** @ignore */
  24391. Scene.prototype.getRenderDuration = function () {
  24392. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24393. return 0;
  24394. };
  24395. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24396. /** @ignore */
  24397. get: function () {
  24398. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24399. return null;
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. /** @ignore */
  24405. Scene.prototype.getParticlesDuration = function () {
  24406. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24407. return 0;
  24408. };
  24409. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24410. /** @ignore */
  24411. get: function () {
  24412. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24413. return null;
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. /** @ignore */
  24419. Scene.prototype.getSpritesDuration = function () {
  24420. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24421. return 0;
  24422. };
  24423. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24424. /** @ignore */
  24425. get: function () {
  24426. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24427. return null;
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. /**
  24433. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24434. * @returns a number
  24435. */
  24436. Scene.prototype.getAnimationRatio = function () {
  24437. return this._animationRatio;
  24438. };
  24439. /**
  24440. * Gets an unique Id for the current frame
  24441. * @returns a number
  24442. */
  24443. Scene.prototype.getRenderId = function () {
  24444. return this._renderId;
  24445. };
  24446. /** Call this function if you want to manually increment the render Id*/
  24447. Scene.prototype.incrementRenderId = function () {
  24448. this._renderId++;
  24449. };
  24450. Scene.prototype._updatePointerPosition = function (evt) {
  24451. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24452. if (!canvasRect) {
  24453. return;
  24454. }
  24455. this._pointerX = evt.clientX - canvasRect.left;
  24456. this._pointerY = evt.clientY - canvasRect.top;
  24457. this._unTranslatedPointerX = this._pointerX;
  24458. this._unTranslatedPointerY = this._pointerY;
  24459. };
  24460. Scene.prototype._createUbo = function () {
  24461. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24462. this._sceneUbo.addUniform("viewProjection", 16);
  24463. this._sceneUbo.addUniform("view", 16);
  24464. };
  24465. Scene.prototype._createAlternateUbo = function () {
  24466. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24467. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24468. this._alternateSceneUbo.addUniform("view", 16);
  24469. };
  24470. // Pointers handling
  24471. /**
  24472. * Use this method to simulate a pointer move on a mesh
  24473. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24474. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24475. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24476. * @returns the current scene
  24477. */
  24478. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24479. var evt = new PointerEvent("pointermove", pointerEventInit);
  24480. return this._processPointerMove(pickResult, evt);
  24481. };
  24482. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24483. var canvas = this._engine.getRenderingCanvas();
  24484. if (!canvas) {
  24485. return this;
  24486. }
  24487. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24488. this.setPointerOverSprite(null);
  24489. this.setPointerOverMesh(pickResult.pickedMesh);
  24490. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24491. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24492. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24493. }
  24494. else {
  24495. canvas.style.cursor = this.hoverCursor;
  24496. }
  24497. }
  24498. else {
  24499. canvas.style.cursor = this.defaultCursor;
  24500. }
  24501. }
  24502. else {
  24503. this.setPointerOverMesh(null);
  24504. // Sprites
  24505. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24506. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24507. this.setPointerOverSprite(pickResult.pickedSprite);
  24508. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24509. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24510. }
  24511. else {
  24512. canvas.style.cursor = this.hoverCursor;
  24513. }
  24514. }
  24515. else {
  24516. this.setPointerOverSprite(null);
  24517. // Restore pointer
  24518. canvas.style.cursor = this.defaultCursor;
  24519. }
  24520. }
  24521. if (pickResult) {
  24522. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24523. if (this.onPointerMove) {
  24524. this.onPointerMove(evt, pickResult, type);
  24525. }
  24526. if (this.onPointerObservable.hasObservers()) {
  24527. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24528. this.onPointerObservable.notifyObservers(pi, type);
  24529. }
  24530. }
  24531. return this;
  24532. };
  24533. /**
  24534. * Use this method to simulate a pointer down on a mesh
  24535. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24536. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24537. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24538. * @returns the current scene
  24539. */
  24540. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24541. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24542. return this._processPointerDown(pickResult, evt);
  24543. };
  24544. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24545. var _this = this;
  24546. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24547. this._pickedDownMesh = pickResult.pickedMesh;
  24548. var actionManager = pickResult.pickedMesh.actionManager;
  24549. if (actionManager) {
  24550. if (actionManager.hasPickTriggers) {
  24551. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24552. switch (evt.button) {
  24553. case 0:
  24554. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24555. break;
  24556. case 1:
  24557. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24558. break;
  24559. case 2:
  24560. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24561. break;
  24562. }
  24563. }
  24564. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24565. window.setTimeout(function () {
  24566. 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);
  24567. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24568. if (_this._totalPointersPressed !== 0 &&
  24569. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24570. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24571. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24572. _this._startingPointerTime = 0;
  24573. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24574. }
  24575. }
  24576. }, Scene.LongPressDelay);
  24577. }
  24578. }
  24579. }
  24580. if (pickResult) {
  24581. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24582. if (this.onPointerDown) {
  24583. this.onPointerDown(evt, pickResult, type);
  24584. }
  24585. if (this.onPointerObservable.hasObservers()) {
  24586. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24587. this.onPointerObservable.notifyObservers(pi, type);
  24588. }
  24589. }
  24590. return this;
  24591. };
  24592. /**
  24593. * Use this method to simulate a pointer up on a mesh
  24594. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24595. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24596. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24597. * @returns the current scene
  24598. */
  24599. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24600. var evt = new PointerEvent("pointerup", pointerEventInit);
  24601. var clickInfo = new ClickInfo();
  24602. clickInfo.singleClick = true;
  24603. clickInfo.ignore = true;
  24604. return this._processPointerUp(pickResult, evt, clickInfo);
  24605. };
  24606. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24607. if (pickResult && pickResult && pickResult.pickedMesh) {
  24608. this._pickedUpMesh = pickResult.pickedMesh;
  24609. if (this._pickedDownMesh === this._pickedUpMesh) {
  24610. if (this.onPointerPick) {
  24611. this.onPointerPick(evt, pickResult);
  24612. }
  24613. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24614. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24615. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24616. this.onPointerObservable.notifyObservers(pi, type_1);
  24617. }
  24618. }
  24619. if (pickResult.pickedMesh.actionManager) {
  24620. if (clickInfo.ignore) {
  24621. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24622. }
  24623. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24624. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24625. }
  24626. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24627. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24628. }
  24629. }
  24630. }
  24631. if (this._pickedDownMesh &&
  24632. this._pickedDownMesh.actionManager &&
  24633. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24634. this._pickedDownMesh !== this._pickedUpMesh) {
  24635. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24636. }
  24637. var type = BABYLON.PointerEventTypes.POINTERUP;
  24638. if (this.onPointerObservable.hasObservers()) {
  24639. if (!clickInfo.ignore) {
  24640. if (!clickInfo.hasSwiped) {
  24641. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24642. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24643. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24644. this.onPointerObservable.notifyObservers(pi, type_2);
  24645. }
  24646. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24647. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24648. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24649. this.onPointerObservable.notifyObservers(pi, type_3);
  24650. }
  24651. }
  24652. }
  24653. else {
  24654. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24655. this.onPointerObservable.notifyObservers(pi, type);
  24656. }
  24657. }
  24658. if (this.onPointerUp) {
  24659. this.onPointerUp(evt, pickResult, type);
  24660. }
  24661. return this;
  24662. };
  24663. /**
  24664. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24665. * @param attachUp defines if you want to attach events to pointerup
  24666. * @param attachDown defines if you want to attach events to pointerdown
  24667. * @param attachMove defines if you want to attach events to pointermove
  24668. */
  24669. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24670. var _this = this;
  24671. if (attachUp === void 0) { attachUp = true; }
  24672. if (attachDown === void 0) { attachDown = true; }
  24673. if (attachMove === void 0) { attachMove = true; }
  24674. this._initActionManager = function (act, clickInfo) {
  24675. if (!_this._meshPickProceed) {
  24676. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24677. _this._currentPickResult = pickResult;
  24678. if (pickResult) {
  24679. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24680. }
  24681. _this._meshPickProceed = true;
  24682. }
  24683. return act;
  24684. };
  24685. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24686. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24687. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24688. btn !== _this._previousButtonPressed) {
  24689. _this._doubleClickOccured = false;
  24690. clickInfo.singleClick = true;
  24691. clickInfo.ignore = false;
  24692. cb(clickInfo, _this._currentPickResult);
  24693. }
  24694. };
  24695. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24696. var clickInfo = new ClickInfo();
  24697. _this._currentPickResult = null;
  24698. var act = null;
  24699. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24700. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24701. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24702. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24703. act = _this._initActionManager(act, clickInfo);
  24704. if (act)
  24705. checkPicking = act.hasPickTriggers;
  24706. }
  24707. if (checkPicking) {
  24708. var btn = evt.button;
  24709. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24710. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24711. if (!clickInfo.hasSwiped) {
  24712. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24713. if (!checkSingleClickImmediately) {
  24714. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24715. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24716. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24717. act = _this._initActionManager(act, clickInfo);
  24718. if (act)
  24719. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24720. }
  24721. }
  24722. if (checkSingleClickImmediately) {
  24723. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24724. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24725. btn !== _this._previousButtonPressed) {
  24726. clickInfo.singleClick = true;
  24727. cb(clickInfo, _this._currentPickResult);
  24728. }
  24729. }
  24730. else {
  24731. // wait that no double click has been raised during the double click delay
  24732. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24733. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24734. }
  24735. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24736. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24737. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24738. act = _this._initActionManager(act, clickInfo);
  24739. if (act)
  24740. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24741. }
  24742. if (checkDoubleClick) {
  24743. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24744. if (btn === _this._previousButtonPressed &&
  24745. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24746. !_this._doubleClickOccured) {
  24747. // pointer has not moved for 2 clicks, it's a double click
  24748. if (!clickInfo.hasSwiped &&
  24749. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24750. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24751. _this._previousStartingPointerTime = 0;
  24752. _this._doubleClickOccured = true;
  24753. clickInfo.doubleClick = true;
  24754. clickInfo.ignore = false;
  24755. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24756. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24757. }
  24758. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24759. cb(clickInfo, _this._currentPickResult);
  24760. }
  24761. else {
  24762. _this._doubleClickOccured = false;
  24763. _this._previousStartingPointerTime = _this._startingPointerTime;
  24764. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24765. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24766. _this._previousButtonPressed = btn;
  24767. if (Scene.ExclusiveDoubleClickMode) {
  24768. if (_this._previousDelayedSimpleClickTimeout) {
  24769. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24770. }
  24771. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24772. cb(clickInfo, _this._previousPickResult);
  24773. }
  24774. else {
  24775. cb(clickInfo, _this._currentPickResult);
  24776. }
  24777. }
  24778. }
  24779. else {
  24780. _this._doubleClickOccured = false;
  24781. _this._previousStartingPointerTime = _this._startingPointerTime;
  24782. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24783. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24784. _this._previousButtonPressed = btn;
  24785. }
  24786. }
  24787. }
  24788. }
  24789. clickInfo.ignore = true;
  24790. cb(clickInfo, _this._currentPickResult);
  24791. };
  24792. this._spritePredicate = function (sprite) {
  24793. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24794. };
  24795. this._onPointerMove = function (evt) {
  24796. _this._updatePointerPosition(evt);
  24797. // PreObservable support
  24798. if (_this.onPrePointerObservable.hasObservers()) {
  24799. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24800. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24801. _this.onPrePointerObservable.notifyObservers(pi, type);
  24802. if (pi.skipOnPointerObservable) {
  24803. return;
  24804. }
  24805. }
  24806. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24807. return;
  24808. }
  24809. if (!_this.pointerMovePredicate) {
  24810. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24811. }
  24812. // Meshes
  24813. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24814. _this._processPointerMove(pickResult, evt);
  24815. };
  24816. this._onPointerDown = function (evt) {
  24817. _this._totalPointersPressed++;
  24818. _this._pickedDownMesh = null;
  24819. _this._meshPickProceed = false;
  24820. _this._updatePointerPosition(evt);
  24821. if (_this.preventDefaultOnPointerDown && canvas) {
  24822. evt.preventDefault();
  24823. canvas.focus();
  24824. }
  24825. // PreObservable support
  24826. if (_this.onPrePointerObservable.hasObservers()) {
  24827. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24828. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24829. _this.onPrePointerObservable.notifyObservers(pi, type);
  24830. if (pi.skipOnPointerObservable) {
  24831. return;
  24832. }
  24833. }
  24834. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24835. return;
  24836. }
  24837. _this._startingPointerPosition.x = _this._pointerX;
  24838. _this._startingPointerPosition.y = _this._pointerY;
  24839. _this._startingPointerTime = new Date().getTime();
  24840. if (!_this.pointerDownPredicate) {
  24841. _this.pointerDownPredicate = function (mesh) {
  24842. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24843. };
  24844. }
  24845. // Meshes
  24846. _this._pickedDownMesh = null;
  24847. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24848. _this._processPointerDown(pickResult, evt);
  24849. // Sprites
  24850. _this._pickedDownSprite = null;
  24851. if (_this.spriteManagers.length > 0) {
  24852. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24853. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24854. if (pickResult.pickedSprite.actionManager) {
  24855. _this._pickedDownSprite = pickResult.pickedSprite;
  24856. switch (evt.button) {
  24857. case 0:
  24858. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24859. break;
  24860. case 1:
  24861. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24862. break;
  24863. case 2:
  24864. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24865. break;
  24866. }
  24867. if (pickResult.pickedSprite.actionManager) {
  24868. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24869. }
  24870. }
  24871. }
  24872. }
  24873. };
  24874. this._onPointerUp = function (evt) {
  24875. if (_this._totalPointersPressed === 0) {
  24876. return; // So we need to test it the pointer down was pressed before.
  24877. }
  24878. _this._totalPointersPressed--;
  24879. _this._pickedUpMesh = null;
  24880. _this._meshPickProceed = false;
  24881. _this._updatePointerPosition(evt);
  24882. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24883. // PreObservable support
  24884. if (_this.onPrePointerObservable.hasObservers()) {
  24885. if (!clickInfo.ignore) {
  24886. if (!clickInfo.hasSwiped) {
  24887. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24888. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24889. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24890. _this.onPrePointerObservable.notifyObservers(pi, type);
  24891. if (pi.skipOnPointerObservable) {
  24892. return;
  24893. }
  24894. }
  24895. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24896. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24897. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24898. _this.onPrePointerObservable.notifyObservers(pi, type);
  24899. if (pi.skipOnPointerObservable) {
  24900. return;
  24901. }
  24902. }
  24903. }
  24904. }
  24905. else {
  24906. var type = BABYLON.PointerEventTypes.POINTERUP;
  24907. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24908. _this.onPrePointerObservable.notifyObservers(pi, type);
  24909. if (pi.skipOnPointerObservable) {
  24910. return;
  24911. }
  24912. }
  24913. }
  24914. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24915. return;
  24916. }
  24917. if (!_this.pointerUpPredicate) {
  24918. _this.pointerUpPredicate = function (mesh) {
  24919. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24920. };
  24921. }
  24922. // Meshes
  24923. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24924. _this._initActionManager(null, clickInfo);
  24925. }
  24926. if (!pickResult) {
  24927. pickResult = _this._currentPickResult;
  24928. }
  24929. _this._processPointerUp(pickResult, evt, clickInfo);
  24930. // Sprites
  24931. if (_this.spriteManagers.length > 0) {
  24932. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24933. if (spritePickResult) {
  24934. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24935. if (spritePickResult.pickedSprite.actionManager) {
  24936. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24937. if (spritePickResult.pickedSprite.actionManager) {
  24938. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24939. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24940. }
  24941. }
  24942. }
  24943. }
  24944. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24945. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24946. }
  24947. }
  24948. }
  24949. _this._previousPickResult = _this._currentPickResult;
  24950. });
  24951. };
  24952. this._onKeyDown = function (evt) {
  24953. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24954. if (_this.onPreKeyboardObservable.hasObservers()) {
  24955. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24956. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24957. if (pi.skipOnPointerObservable) {
  24958. return;
  24959. }
  24960. }
  24961. if (_this.onKeyboardObservable.hasObservers()) {
  24962. var pi = new BABYLON.KeyboardInfo(type, evt);
  24963. _this.onKeyboardObservable.notifyObservers(pi, type);
  24964. }
  24965. if (_this.actionManager) {
  24966. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24967. }
  24968. };
  24969. this._onKeyUp = function (evt) {
  24970. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24971. if (_this.onPreKeyboardObservable.hasObservers()) {
  24972. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24973. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24974. if (pi.skipOnPointerObservable) {
  24975. return;
  24976. }
  24977. }
  24978. if (_this.onKeyboardObservable.hasObservers()) {
  24979. var pi = new BABYLON.KeyboardInfo(type, evt);
  24980. _this.onKeyboardObservable.notifyObservers(pi, type);
  24981. }
  24982. if (_this.actionManager) {
  24983. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24984. }
  24985. };
  24986. var engine = this.getEngine();
  24987. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24988. if (!canvas) {
  24989. return;
  24990. }
  24991. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24992. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24993. });
  24994. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24995. if (!canvas) {
  24996. return;
  24997. }
  24998. canvas.removeEventListener("keydown", _this._onKeyDown);
  24999. canvas.removeEventListener("keyup", _this._onKeyUp);
  25000. });
  25001. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25002. var canvas = this._engine.getRenderingCanvas();
  25003. if (!canvas) {
  25004. return;
  25005. }
  25006. if (attachMove) {
  25007. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25008. // Wheel
  25009. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25010. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25011. }
  25012. if (attachDown) {
  25013. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25014. }
  25015. if (attachUp) {
  25016. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25017. }
  25018. canvas.tabIndex = 1;
  25019. };
  25020. /** Detaches all event handlers*/
  25021. Scene.prototype.detachControl = function () {
  25022. var engine = this.getEngine();
  25023. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25024. var canvas = engine.getRenderingCanvas();
  25025. if (!canvas) {
  25026. return;
  25027. }
  25028. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25029. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25030. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25031. if (this._onCanvasBlurObserver) {
  25032. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25033. }
  25034. if (this._onCanvasFocusObserver) {
  25035. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25036. }
  25037. // Wheel
  25038. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25039. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25040. // Keyboard
  25041. canvas.removeEventListener("keydown", this._onKeyDown);
  25042. canvas.removeEventListener("keyup", this._onKeyUp);
  25043. // Observables
  25044. this.onKeyboardObservable.clear();
  25045. this.onPreKeyboardObservable.clear();
  25046. this.onPointerObservable.clear();
  25047. this.onPrePointerObservable.clear();
  25048. };
  25049. /**
  25050. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25051. * Delay loaded resources are not taking in account
  25052. * @return true if all required resources are ready
  25053. */
  25054. Scene.prototype.isReady = function () {
  25055. if (this._isDisposed) {
  25056. return false;
  25057. }
  25058. if (this._pendingData.length > 0) {
  25059. return false;
  25060. }
  25061. var index;
  25062. var engine = this.getEngine();
  25063. // Geometries
  25064. for (index = 0; index < this._geometries.length; index++) {
  25065. var geometry = this._geometries[index];
  25066. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25067. return false;
  25068. }
  25069. }
  25070. // Meshes
  25071. for (index = 0; index < this.meshes.length; index++) {
  25072. var mesh = this.meshes[index];
  25073. if (!mesh.isEnabled()) {
  25074. continue;
  25075. }
  25076. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25077. continue;
  25078. }
  25079. if (!mesh.isReady(true)) {
  25080. return false;
  25081. }
  25082. // Effect layers
  25083. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25084. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25085. var layer = _a[_i];
  25086. if (!layer.hasMesh(mesh)) {
  25087. continue;
  25088. }
  25089. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25090. var subMesh = _c[_b];
  25091. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25092. return false;
  25093. }
  25094. }
  25095. }
  25096. }
  25097. // Post-processes
  25098. if (this.activeCameras && this.activeCameras.length > 0) {
  25099. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25100. var camera = _e[_d];
  25101. if (!camera.isReady(true)) {
  25102. return false;
  25103. }
  25104. }
  25105. }
  25106. else if (this.activeCamera) {
  25107. if (!this.activeCamera.isReady(true)) {
  25108. return false;
  25109. }
  25110. }
  25111. // Particles
  25112. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25113. var particleSystem = _g[_f];
  25114. if (!particleSystem.isReady()) {
  25115. return false;
  25116. }
  25117. }
  25118. return true;
  25119. };
  25120. /** Resets all cached information relative to material (including effect and visibility) */
  25121. Scene.prototype.resetCachedMaterial = function () {
  25122. this._cachedMaterial = null;
  25123. this._cachedEffect = null;
  25124. this._cachedVisibility = null;
  25125. };
  25126. /**
  25127. * Registers a function to be called before every frame render
  25128. * @param func defines the function to register
  25129. */
  25130. Scene.prototype.registerBeforeRender = function (func) {
  25131. this.onBeforeRenderObservable.add(func);
  25132. };
  25133. /**
  25134. * Unregisters a function called before every frame render
  25135. * @param func defines the function to unregister
  25136. */
  25137. Scene.prototype.unregisterBeforeRender = function (func) {
  25138. this.onBeforeRenderObservable.removeCallback(func);
  25139. };
  25140. /**
  25141. * Registers a function to be called after every frame render
  25142. * @param func defines the function to register
  25143. */
  25144. Scene.prototype.registerAfterRender = function (func) {
  25145. this.onAfterRenderObservable.add(func);
  25146. };
  25147. /**
  25148. * Unregisters a function called after every frame render
  25149. * @param func defines the function to unregister
  25150. */
  25151. Scene.prototype.unregisterAfterRender = function (func) {
  25152. this.onAfterRenderObservable.removeCallback(func);
  25153. };
  25154. Scene.prototype._executeOnceBeforeRender = function (func) {
  25155. var _this = this;
  25156. var execFunc = function () {
  25157. func();
  25158. setTimeout(function () {
  25159. _this.unregisterBeforeRender(execFunc);
  25160. });
  25161. };
  25162. this.registerBeforeRender(execFunc);
  25163. };
  25164. /**
  25165. * The provided function will run before render once and will be disposed afterwards.
  25166. * A timeout delay can be provided so that the function will be executed in N ms.
  25167. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25168. * @param func The function to be executed.
  25169. * @param timeout optional delay in ms
  25170. */
  25171. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25172. var _this = this;
  25173. if (timeout !== undefined) {
  25174. setTimeout(function () {
  25175. _this._executeOnceBeforeRender(func);
  25176. }, timeout);
  25177. }
  25178. else {
  25179. this._executeOnceBeforeRender(func);
  25180. }
  25181. };
  25182. /** @ignore */
  25183. Scene.prototype._addPendingData = function (data) {
  25184. this._pendingData.push(data);
  25185. };
  25186. /** @ignore */
  25187. Scene.prototype._removePendingData = function (data) {
  25188. var wasLoading = this.isLoading;
  25189. var index = this._pendingData.indexOf(data);
  25190. if (index !== -1) {
  25191. this._pendingData.splice(index, 1);
  25192. }
  25193. if (wasLoading && !this.isLoading) {
  25194. this.onDataLoadedObservable.notifyObservers(this);
  25195. }
  25196. };
  25197. /**
  25198. * Returns the number of items waiting to be loaded
  25199. * @returns the number of items waiting to be loaded
  25200. */
  25201. Scene.prototype.getWaitingItemsCount = function () {
  25202. return this._pendingData.length;
  25203. };
  25204. Object.defineProperty(Scene.prototype, "isLoading", {
  25205. /**
  25206. * Returns a boolean indicating if the scene is still loading data
  25207. */
  25208. get: function () {
  25209. return this._pendingData.length > 0;
  25210. },
  25211. enumerable: true,
  25212. configurable: true
  25213. });
  25214. /**
  25215. * Registers a function to be executed when the scene is ready
  25216. * @param {Function} func - the function to be executed
  25217. */
  25218. Scene.prototype.executeWhenReady = function (func) {
  25219. var _this = this;
  25220. this.onReadyObservable.add(func);
  25221. if (this._executeWhenReadyTimeoutId !== -1) {
  25222. return;
  25223. }
  25224. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25225. _this._checkIsReady();
  25226. }, 150);
  25227. };
  25228. /**
  25229. * Returns a promise that resolves when the scene is ready
  25230. * @returns A promise that resolves when the scene is ready
  25231. */
  25232. Scene.prototype.whenReadyAsync = function () {
  25233. var _this = this;
  25234. return new Promise(function (resolve) {
  25235. _this.executeWhenReady(function () {
  25236. resolve();
  25237. });
  25238. });
  25239. };
  25240. /** @ignore */
  25241. Scene.prototype._checkIsReady = function () {
  25242. var _this = this;
  25243. if (this.isReady()) {
  25244. this.onReadyObservable.notifyObservers(this);
  25245. this.onReadyObservable.clear();
  25246. this._executeWhenReadyTimeoutId = -1;
  25247. return;
  25248. }
  25249. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25250. _this._checkIsReady();
  25251. }, 150);
  25252. };
  25253. // Animations
  25254. /**
  25255. * Will start the animation sequence of a given target
  25256. * @param target defines the target
  25257. * @param from defines from which frame should animation start
  25258. * @param to defines until which frame should animation run.
  25259. * @param weight defines the weight to apply to the animation (1.0 by default)
  25260. * @param loop defines if the animation loops
  25261. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25262. * @param onAnimationEnd defines the function to be executed when the animation ends
  25263. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25264. * @returns the animatable object created for this animation
  25265. */
  25266. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25267. if (weight === void 0) { weight = 1.0; }
  25268. if (speedRatio === void 0) { speedRatio = 1.0; }
  25269. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25270. returnedAnimatable.weight = weight;
  25271. return returnedAnimatable;
  25272. };
  25273. /**
  25274. * Will start the animation sequence of a given target
  25275. * @param target defines the target
  25276. * @param from defines from which frame should animation start
  25277. * @param to defines until which frame should animation run.
  25278. * @param loop defines if the animation loops
  25279. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25280. * @param onAnimationEnd defines the function to be executed when the animation ends
  25281. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25282. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25283. * @returns the animatable object created for this animation
  25284. */
  25285. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25286. if (speedRatio === void 0) { speedRatio = 1.0; }
  25287. if (stopCurrent === void 0) { stopCurrent = true; }
  25288. if (from > to && speedRatio > 0) {
  25289. speedRatio *= -1;
  25290. }
  25291. if (stopCurrent) {
  25292. this.stopAnimation(target);
  25293. }
  25294. if (!animatable) {
  25295. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25296. }
  25297. // Local animations
  25298. if (target.animations) {
  25299. animatable.appendAnimations(target, target.animations);
  25300. }
  25301. // Children animations
  25302. if (target.getAnimatables) {
  25303. var animatables = target.getAnimatables();
  25304. for (var index = 0; index < animatables.length; index++) {
  25305. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25306. }
  25307. }
  25308. animatable.reset();
  25309. return animatable;
  25310. };
  25311. /**
  25312. * Begin a new animation on a given node
  25313. * @param target defines the target where the animation will take place
  25314. * @param animations defines the list of animations to start
  25315. * @param from defines the initial value
  25316. * @param to defines the final value
  25317. * @param loop defines if you want animation to loop (off by default)
  25318. * @param speedRatio defines the speed ratio to apply to all animations
  25319. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25320. * @returns the list of created animatables
  25321. */
  25322. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25323. if (speedRatio === undefined) {
  25324. speedRatio = 1.0;
  25325. }
  25326. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25327. return animatable;
  25328. };
  25329. /**
  25330. * Begin a new animation on a given node and its hierarchy
  25331. * @param target defines the root node where the animation will take place
  25332. * @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.
  25333. * @param animations defines the list of animations to start
  25334. * @param from defines the initial value
  25335. * @param to defines the final value
  25336. * @param loop defines if you want animation to loop (off by default)
  25337. * @param speedRatio defines the speed ratio to apply to all animations
  25338. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25339. * @returns the list of animatables created for all nodes
  25340. */
  25341. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25342. var children = target.getDescendants(directDescendantsOnly);
  25343. var result = [];
  25344. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25345. var child = children_1[_i];
  25346. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25347. }
  25348. return result;
  25349. };
  25350. /**
  25351. * Gets the animatable associated with a specific target
  25352. * @param target defines the target of the animatable
  25353. * @returns the required animatable if found
  25354. */
  25355. Scene.prototype.getAnimatableByTarget = function (target) {
  25356. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25357. if (this._activeAnimatables[index].target === target) {
  25358. return this._activeAnimatables[index];
  25359. }
  25360. }
  25361. return null;
  25362. };
  25363. /**
  25364. * Gets all animatables associated with a given target
  25365. * @param target defines the target to look animatables for
  25366. * @returns an array of Animatables
  25367. */
  25368. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25369. var result = [];
  25370. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25371. if (this._activeAnimatables[index].target === target) {
  25372. result.push(this._activeAnimatables[index]);
  25373. }
  25374. }
  25375. return result;
  25376. };
  25377. Object.defineProperty(Scene.prototype, "animatables", {
  25378. /**
  25379. * Gets all animatable attached to the scene
  25380. */
  25381. get: function () {
  25382. return this._activeAnimatables;
  25383. },
  25384. enumerable: true,
  25385. configurable: true
  25386. });
  25387. /**
  25388. * Will stop the animation of the given target
  25389. * @param target - the target
  25390. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25391. */
  25392. Scene.prototype.stopAnimation = function (target, animationName) {
  25393. var animatables = this.getAllAnimatablesByTarget(target);
  25394. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25395. var animatable = animatables_1[_i];
  25396. animatable.stop(animationName);
  25397. }
  25398. };
  25399. /**
  25400. * Stops and removes all animations that have been applied to the scene
  25401. */
  25402. Scene.prototype.stopAllAnimations = function () {
  25403. if (this._activeAnimatables) {
  25404. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25405. this._activeAnimatables[i].stop();
  25406. }
  25407. this._activeAnimatables = [];
  25408. }
  25409. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25410. var group = _a[_i];
  25411. group.stop();
  25412. }
  25413. };
  25414. Scene.prototype._animate = function () {
  25415. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25416. return;
  25417. }
  25418. // Getting time
  25419. var now = BABYLON.Tools.Now;
  25420. if (!this._animationTimeLast) {
  25421. if (this._pendingData.length > 0) {
  25422. return;
  25423. }
  25424. this._animationTimeLast = now;
  25425. }
  25426. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25427. this._animationTime += deltaTime;
  25428. this._animationTimeLast = now;
  25429. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25430. this._activeAnimatables[index]._animate(this._animationTime);
  25431. }
  25432. // Late animation bindings
  25433. this._processLateAnimationBindings();
  25434. };
  25435. /** @ignore */
  25436. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25437. var target = runtimeAnimation.target;
  25438. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25439. if (!target._lateAnimationHolders) {
  25440. target._lateAnimationHolders = {};
  25441. }
  25442. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25443. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25444. totalWeight: 0,
  25445. animations: []
  25446. };
  25447. }
  25448. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25449. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25450. };
  25451. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25452. var normalizer = 1.0;
  25453. var finalPosition = BABYLON.Tmp.Vector3[0];
  25454. var finalScaling = BABYLON.Tmp.Vector3[1];
  25455. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25456. var startIndex = 0;
  25457. var originalAnimation = holder.animations[0];
  25458. var scale = 1;
  25459. if (holder.totalWeight < 1.0) {
  25460. // We need to mix the original value in
  25461. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25462. scale = 1.0 - holder.totalWeight;
  25463. }
  25464. else {
  25465. startIndex = 1;
  25466. // We need to normalize the weights
  25467. normalizer = holder.totalWeight;
  25468. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25469. scale = originalAnimation.weight / normalizer;
  25470. if (scale == 1) {
  25471. return originalAnimation.currentValue;
  25472. }
  25473. }
  25474. finalScaling.scaleInPlace(scale);
  25475. finalPosition.scaleInPlace(scale);
  25476. finalQuaternion.scaleInPlace(scale);
  25477. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25478. var runtimeAnimation = holder.animations[animIndex];
  25479. var scale = runtimeAnimation.weight / normalizer;
  25480. var currentPosition = BABYLON.Tmp.Vector3[2];
  25481. var currentScaling = BABYLON.Tmp.Vector3[3];
  25482. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25483. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25484. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25485. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25486. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25487. }
  25488. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25489. return originalAnimation._workValue;
  25490. };
  25491. Scene.prototype._processLateAnimationBindings = function () {
  25492. if (!this._registeredForLateAnimationBindings.length) {
  25493. return;
  25494. }
  25495. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25496. var target = this._registeredForLateAnimationBindings.data[index];
  25497. for (var path in target._lateAnimationHolders) {
  25498. var holder = target._lateAnimationHolders[path];
  25499. var originalAnimation = holder.animations[0];
  25500. var originalValue = originalAnimation.originalValue;
  25501. var finalTarget = originalAnimation.target;
  25502. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25503. var finalValue = void 0;
  25504. if (matrixDecomposeMode) {
  25505. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25506. }
  25507. else {
  25508. var startIndex = 0;
  25509. var normalizer = 1.0;
  25510. if (holder.totalWeight < 1.0) {
  25511. // We need to mix the original value in
  25512. if (originalValue.scale) {
  25513. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25514. }
  25515. else {
  25516. finalValue = originalValue * (1.0 - holder.totalWeight);
  25517. }
  25518. }
  25519. else {
  25520. // We need to normalize the weights
  25521. normalizer = holder.totalWeight;
  25522. var scale_1 = originalAnimation.weight / normalizer;
  25523. if (scale_1 !== 1) {
  25524. if (originalAnimation.currentValue.scale) {
  25525. finalValue = originalAnimation.currentValue.scale(scale_1);
  25526. }
  25527. else {
  25528. finalValue = originalAnimation.currentValue * scale_1;
  25529. }
  25530. }
  25531. else {
  25532. finalValue = originalAnimation.currentValue;
  25533. }
  25534. startIndex = 1;
  25535. }
  25536. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25537. var runtimeAnimation = holder.animations[animIndex];
  25538. var scale = runtimeAnimation.weight / normalizer;
  25539. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25540. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25541. }
  25542. else {
  25543. finalValue += runtimeAnimation.currentValue * scale;
  25544. }
  25545. }
  25546. }
  25547. finalTarget[path] = finalValue;
  25548. }
  25549. target._lateAnimationHolders = {};
  25550. }
  25551. this._registeredForLateAnimationBindings.reset();
  25552. };
  25553. // Matrix
  25554. /** @ignore */
  25555. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25556. this._useAlternateCameraConfiguration = active;
  25557. };
  25558. /**
  25559. * Gets the current view matrix
  25560. * @returns a Matrix
  25561. */
  25562. Scene.prototype.getViewMatrix = function () {
  25563. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25564. };
  25565. /**
  25566. * Gets the current projection matrix
  25567. * @returns a Matrix
  25568. */
  25569. Scene.prototype.getProjectionMatrix = function () {
  25570. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25571. };
  25572. /**
  25573. * Gets the current transform matrix
  25574. * @returns a Matrix made of View * Projection
  25575. */
  25576. Scene.prototype.getTransformMatrix = function () {
  25577. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25578. };
  25579. /**
  25580. * Sets the current transform matrix
  25581. * @param view defines the View matrix to use
  25582. * @param projection defines the Projection matrix to use
  25583. */
  25584. Scene.prototype.setTransformMatrix = function (view, projection) {
  25585. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25586. return;
  25587. }
  25588. this._viewUpdateFlag = view.updateFlag;
  25589. this._projectionUpdateFlag = projection.updateFlag;
  25590. this._viewMatrix = view;
  25591. this._projectionMatrix = projection;
  25592. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25593. // Update frustum
  25594. if (!this._frustumPlanes) {
  25595. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25596. }
  25597. else {
  25598. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25599. }
  25600. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25601. var otherCamera = this.activeCamera._alternateCamera;
  25602. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25603. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25604. }
  25605. if (this._sceneUbo.useUbo) {
  25606. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25607. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25608. this._sceneUbo.update();
  25609. }
  25610. };
  25611. /** @ignore */
  25612. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25613. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25614. return;
  25615. }
  25616. this._alternateViewUpdateFlag = view.updateFlag;
  25617. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25618. this._alternateViewMatrix = view;
  25619. this._alternateProjectionMatrix = projection;
  25620. if (!this._alternateTransformMatrix) {
  25621. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25622. }
  25623. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25624. if (!this._alternateSceneUbo) {
  25625. this._createAlternateUbo();
  25626. }
  25627. if (this._alternateSceneUbo.useUbo) {
  25628. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25629. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25630. this._alternateSceneUbo.update();
  25631. }
  25632. };
  25633. /**
  25634. * Gets the uniform buffer used to store scene data
  25635. * @returns a UniformBuffer
  25636. */
  25637. Scene.prototype.getSceneUniformBuffer = function () {
  25638. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25639. };
  25640. /**
  25641. * Gets an unique (relatively to the current scene) Id
  25642. * @returns an unique number for the scene
  25643. */
  25644. Scene.prototype.getUniqueId = function () {
  25645. var result = Scene._uniqueIdCounter;
  25646. Scene._uniqueIdCounter++;
  25647. return result;
  25648. };
  25649. /**
  25650. * Add a mesh to the list of scene's meshes
  25651. * @param newMesh defines the mesh to add
  25652. */
  25653. Scene.prototype.addMesh = function (newMesh) {
  25654. this.meshes.push(newMesh);
  25655. //notify the collision coordinator
  25656. if (this.collisionCoordinator) {
  25657. this.collisionCoordinator.onMeshAdded(newMesh);
  25658. }
  25659. newMesh._resyncLightSources();
  25660. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25661. };
  25662. /**
  25663. * Remove a mesh for the list of scene's meshes
  25664. * @param toRemove defines the mesh to remove
  25665. * @returns the index where the mesh was in the mesh list
  25666. */
  25667. Scene.prototype.removeMesh = function (toRemove) {
  25668. var index = this.meshes.indexOf(toRemove);
  25669. if (index !== -1) {
  25670. // Remove from the scene if mesh found
  25671. this.meshes.splice(index, 1);
  25672. }
  25673. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25674. return index;
  25675. };
  25676. /**
  25677. * Add a transform node to the list of scene's transform nodes
  25678. * @param newTransformNode defines the transform node to add
  25679. */
  25680. Scene.prototype.addTransformNode = function (newTransformNode) {
  25681. this.transformNodes.push(newTransformNode);
  25682. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25683. };
  25684. /**
  25685. * Remove a transform node for the list of scene's transform nodes
  25686. * @param toRemove defines the transform node to remove
  25687. * @returns the index where the transform node was in the transform node list
  25688. */
  25689. Scene.prototype.removeTransformNode = function (toRemove) {
  25690. var index = this.transformNodes.indexOf(toRemove);
  25691. if (index !== -1) {
  25692. // Remove from the scene if found
  25693. this.transformNodes.splice(index, 1);
  25694. }
  25695. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25696. return index;
  25697. };
  25698. /**
  25699. * Remove a skeleton for the list of scene's skeletons
  25700. * @param toRemove defines the skeleton to remove
  25701. * @returns the index where the skeleton was in the skeleton list
  25702. */
  25703. Scene.prototype.removeSkeleton = function (toRemove) {
  25704. var index = this.skeletons.indexOf(toRemove);
  25705. if (index !== -1) {
  25706. // Remove from the scene if found
  25707. this.skeletons.splice(index, 1);
  25708. }
  25709. return index;
  25710. };
  25711. /**
  25712. * Remove a morph target for the list of scene's morph targets
  25713. * @param toRemove defines the morph target to remove
  25714. * @returns the index where the morph target was in the morph target list
  25715. */
  25716. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25717. var index = this.morphTargetManagers.indexOf(toRemove);
  25718. if (index !== -1) {
  25719. // Remove from the scene if found
  25720. this.morphTargetManagers.splice(index, 1);
  25721. }
  25722. return index;
  25723. };
  25724. /**
  25725. * Remove a light for the list of scene's lights
  25726. * @param toRemove defines the light to remove
  25727. * @returns the index where the light was in the light list
  25728. */
  25729. Scene.prototype.removeLight = function (toRemove) {
  25730. var index = this.lights.indexOf(toRemove);
  25731. if (index !== -1) {
  25732. // Remove from meshes
  25733. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25734. var mesh = _a[_i];
  25735. mesh._removeLightSource(toRemove);
  25736. }
  25737. // Remove from the scene if mesh found
  25738. this.lights.splice(index, 1);
  25739. this.sortLightsByPriority();
  25740. }
  25741. this.onLightRemovedObservable.notifyObservers(toRemove);
  25742. return index;
  25743. };
  25744. /**
  25745. * Remove a camera for the list of scene's cameras
  25746. * @param toRemove defines the camera to remove
  25747. * @returns the index where the camera was in the camera list
  25748. */
  25749. Scene.prototype.removeCamera = function (toRemove) {
  25750. var index = this.cameras.indexOf(toRemove);
  25751. if (index !== -1) {
  25752. // Remove from the scene if mesh found
  25753. this.cameras.splice(index, 1);
  25754. }
  25755. // Remove from activeCameras
  25756. var index2 = this.activeCameras.indexOf(toRemove);
  25757. if (index2 !== -1) {
  25758. // Remove from the scene if mesh found
  25759. this.activeCameras.splice(index2, 1);
  25760. }
  25761. // Reset the activeCamera
  25762. if (this.activeCamera === toRemove) {
  25763. if (this.cameras.length > 0) {
  25764. this.activeCamera = this.cameras[0];
  25765. }
  25766. else {
  25767. this.activeCamera = null;
  25768. }
  25769. }
  25770. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25771. return index;
  25772. };
  25773. /**
  25774. * Remove a particle system for the list of scene's particle systems
  25775. * @param toRemove defines the particle system to remove
  25776. * @returns the index where the particle system was in the particle system list
  25777. */
  25778. Scene.prototype.removeParticleSystem = function (toRemove) {
  25779. var index = this.particleSystems.indexOf(toRemove);
  25780. if (index !== -1) {
  25781. this.particleSystems.splice(index, 1);
  25782. }
  25783. return index;
  25784. };
  25785. /**
  25786. * Remove a animation for the list of scene's animations
  25787. * @param toRemove defines the animation to remove
  25788. * @returns the index where the animation was in the animation list
  25789. */
  25790. Scene.prototype.removeAnimation = function (toRemove) {
  25791. var index = this.animations.indexOf(toRemove);
  25792. if (index !== -1) {
  25793. this.animations.splice(index, 1);
  25794. }
  25795. return index;
  25796. };
  25797. /**
  25798. * Removes the given animation group from this scene.
  25799. * @param toRemove The animation group to remove
  25800. * @returns The index of the removed animation group
  25801. */
  25802. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25803. var index = this.animationGroups.indexOf(toRemove);
  25804. if (index !== -1) {
  25805. this.animationGroups.splice(index, 1);
  25806. }
  25807. return index;
  25808. };
  25809. /**
  25810. * Removes the given multi-material from this scene.
  25811. * @param toRemove The multi-material to remove
  25812. * @returns The index of the removed multi-material
  25813. */
  25814. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25815. var index = this.multiMaterials.indexOf(toRemove);
  25816. if (index !== -1) {
  25817. this.multiMaterials.splice(index, 1);
  25818. }
  25819. return index;
  25820. };
  25821. /**
  25822. * Removes the given material from this scene.
  25823. * @param toRemove The material to remove
  25824. * @returns The index of the removed material
  25825. */
  25826. Scene.prototype.removeMaterial = function (toRemove) {
  25827. var index = this.materials.indexOf(toRemove);
  25828. if (index !== -1) {
  25829. this.materials.splice(index, 1);
  25830. }
  25831. return index;
  25832. };
  25833. /**
  25834. * Removes the given lens flare system from this scene.
  25835. * @param toRemove The lens flare system to remove
  25836. * @returns The index of the removed lens flare system
  25837. */
  25838. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25839. var index = this.lensFlareSystems.indexOf(toRemove);
  25840. if (index !== -1) {
  25841. this.lensFlareSystems.splice(index, 1);
  25842. }
  25843. return index;
  25844. };
  25845. /**
  25846. * Removes the given action manager from this scene.
  25847. * @param toRemove The action manager to remove
  25848. * @returns The index of the removed action manager
  25849. */
  25850. Scene.prototype.removeActionManager = function (toRemove) {
  25851. var index = this._actionManagers.indexOf(toRemove);
  25852. if (index !== -1) {
  25853. this._actionManagers.splice(index, 1);
  25854. }
  25855. return index;
  25856. };
  25857. /**
  25858. * Removes the given effect layer from this scene.
  25859. * @param toRemove defines the effect layer to remove
  25860. * @returns the index of the removed effect layer
  25861. */
  25862. Scene.prototype.removeEffectLayer = function (toRemove) {
  25863. var index = this.effectLayers.indexOf(toRemove);
  25864. if (index !== -1) {
  25865. this.effectLayers.splice(index, 1);
  25866. }
  25867. return index;
  25868. };
  25869. /**
  25870. * Removes the given texture from this scene.
  25871. * @param toRemove The texture to remove
  25872. * @returns The index of the removed texture
  25873. */
  25874. Scene.prototype.removeTexture = function (toRemove) {
  25875. var index = this.textures.indexOf(toRemove);
  25876. if (index !== -1) {
  25877. this.textures.splice(index, 1);
  25878. }
  25879. return index;
  25880. };
  25881. /**
  25882. * Adds the given light to this scene
  25883. * @param newLight The light to add
  25884. */
  25885. Scene.prototype.addLight = function (newLight) {
  25886. this.lights.push(newLight);
  25887. this.sortLightsByPriority();
  25888. // Add light to all meshes (To support if the light is removed and then readded)
  25889. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25890. var mesh = _a[_i];
  25891. if (mesh._lightSources.indexOf(newLight) === -1) {
  25892. mesh._lightSources.push(newLight);
  25893. mesh._resyncLightSources();
  25894. }
  25895. }
  25896. this.onNewLightAddedObservable.notifyObservers(newLight);
  25897. };
  25898. /**
  25899. * Sorts the list list based on light priorities
  25900. */
  25901. Scene.prototype.sortLightsByPriority = function () {
  25902. if (this.requireLightSorting) {
  25903. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25904. }
  25905. };
  25906. /**
  25907. * Adds the given camera to this scene
  25908. * @param newCamera The camera to add
  25909. */
  25910. Scene.prototype.addCamera = function (newCamera) {
  25911. this.cameras.push(newCamera);
  25912. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25913. };
  25914. /**
  25915. * Adds the given skeleton to this scene
  25916. * @param newSkeleton The skeleton to add
  25917. */
  25918. Scene.prototype.addSkeleton = function (newSkeleton) {
  25919. this.skeletons.push(newSkeleton);
  25920. };
  25921. /**
  25922. * Adds the given particle system to this scene
  25923. * @param newParticleSystem The particle system to add
  25924. */
  25925. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25926. this.particleSystems.push(newParticleSystem);
  25927. };
  25928. /**
  25929. * Adds the given animation to this scene
  25930. * @param newAnimation The animation to add
  25931. */
  25932. Scene.prototype.addAnimation = function (newAnimation) {
  25933. this.animations.push(newAnimation);
  25934. };
  25935. /**
  25936. * Adds the given animation group to this scene.
  25937. * @param newAnimationGroup The animation group to add
  25938. */
  25939. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25940. this.animationGroups.push(newAnimationGroup);
  25941. };
  25942. /**
  25943. * Adds the given multi-material to this scene
  25944. * @param newMultiMaterial The multi-material to add
  25945. */
  25946. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25947. this.multiMaterials.push(newMultiMaterial);
  25948. };
  25949. /**
  25950. * Adds the given material to this scene
  25951. * @param newMaterial The material to add
  25952. */
  25953. Scene.prototype.addMaterial = function (newMaterial) {
  25954. this.materials.push(newMaterial);
  25955. };
  25956. /**
  25957. * Adds the given morph target to this scene
  25958. * @param newMorphTargetManager The morph target to add
  25959. */
  25960. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25961. this.morphTargetManagers.push(newMorphTargetManager);
  25962. };
  25963. /**
  25964. * Adds the given geometry to this scene
  25965. * @param newGeometry The geometry to add
  25966. */
  25967. Scene.prototype.addGeometry = function (newGeometry) {
  25968. this._geometries.push(newGeometry);
  25969. };
  25970. /**
  25971. * Adds the given lens flare system to this scene
  25972. * @param newLensFlareSystem The lens flare system to add
  25973. */
  25974. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25975. this.lensFlareSystems.push(newLensFlareSystem);
  25976. };
  25977. /**
  25978. * Adds the given effect layer to this scene
  25979. * @param newEffectLayer defines the effect layer to add
  25980. */
  25981. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  25982. this.effectLayers.push(newEffectLayer);
  25983. };
  25984. /**
  25985. * Adds the given action manager to this scene
  25986. * @param newActionManager The action manager to add
  25987. */
  25988. Scene.prototype.addActionManager = function (newActionManager) {
  25989. this._actionManagers.push(newActionManager);
  25990. };
  25991. /**
  25992. * Adds the given texture to this scene.
  25993. * @param newTexture The texture to add
  25994. */
  25995. Scene.prototype.addTexture = function (newTexture) {
  25996. this.textures.push(newTexture);
  25997. };
  25998. /**
  25999. * Switch active camera
  26000. * @param newCamera defines the new active camera
  26001. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26002. */
  26003. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26004. if (attachControl === void 0) { attachControl = true; }
  26005. var canvas = this._engine.getRenderingCanvas();
  26006. if (!canvas) {
  26007. return;
  26008. }
  26009. if (this.activeCamera) {
  26010. this.activeCamera.detachControl(canvas);
  26011. }
  26012. this.activeCamera = newCamera;
  26013. if (attachControl) {
  26014. newCamera.attachControl(canvas);
  26015. }
  26016. };
  26017. /**
  26018. * sets the active camera of the scene using its ID
  26019. * @param id defines the camera's ID
  26020. * @return the new active camera or null if none found.
  26021. */
  26022. Scene.prototype.setActiveCameraByID = function (id) {
  26023. var camera = this.getCameraByID(id);
  26024. if (camera) {
  26025. this.activeCamera = camera;
  26026. return camera;
  26027. }
  26028. return null;
  26029. };
  26030. /**
  26031. * sets the active camera of the scene using its name
  26032. * @param name defines the camera's name
  26033. * @returns the new active camera or null if none found.
  26034. */
  26035. Scene.prototype.setActiveCameraByName = function (name) {
  26036. var camera = this.getCameraByName(name);
  26037. if (camera) {
  26038. this.activeCamera = camera;
  26039. return camera;
  26040. }
  26041. return null;
  26042. };
  26043. /**
  26044. * get an animation group using its name
  26045. * @param name defines the material's name
  26046. * @return the animation group or null if none found.
  26047. */
  26048. Scene.prototype.getAnimationGroupByName = function (name) {
  26049. for (var index = 0; index < this.animationGroups.length; index++) {
  26050. if (this.animationGroups[index].name === name) {
  26051. return this.animationGroups[index];
  26052. }
  26053. }
  26054. return null;
  26055. };
  26056. /**
  26057. * get a material using its id
  26058. * @param id defines the material's ID
  26059. * @return the material or null if none found.
  26060. */
  26061. Scene.prototype.getMaterialByID = function (id) {
  26062. for (var index = 0; index < this.materials.length; index++) {
  26063. if (this.materials[index].id === id) {
  26064. return this.materials[index];
  26065. }
  26066. }
  26067. return null;
  26068. };
  26069. /**
  26070. * Gets a material using its name
  26071. * @param name defines the material's name
  26072. * @return the material or null if none found.
  26073. */
  26074. Scene.prototype.getMaterialByName = function (name) {
  26075. for (var index = 0; index < this.materials.length; index++) {
  26076. if (this.materials[index].name === name) {
  26077. return this.materials[index];
  26078. }
  26079. }
  26080. return null;
  26081. };
  26082. /**
  26083. * Gets a lens flare system using its name
  26084. * @param name defines the name to look for
  26085. * @returns the lens flare system or null if not found
  26086. */
  26087. Scene.prototype.getLensFlareSystemByName = function (name) {
  26088. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26089. if (this.lensFlareSystems[index].name === name) {
  26090. return this.lensFlareSystems[index];
  26091. }
  26092. }
  26093. return null;
  26094. };
  26095. /**
  26096. * Gets a lens flare system using its id
  26097. * @param id defines the id to look for
  26098. * @returns the lens flare system or null if not found
  26099. */
  26100. Scene.prototype.getLensFlareSystemByID = function (id) {
  26101. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26102. if (this.lensFlareSystems[index].id === id) {
  26103. return this.lensFlareSystems[index];
  26104. }
  26105. }
  26106. return null;
  26107. };
  26108. /**
  26109. * Gets a camera using its id
  26110. * @param id defines the id to look for
  26111. * @returns the camera or null if not found
  26112. */
  26113. Scene.prototype.getCameraByID = function (id) {
  26114. for (var index = 0; index < this.cameras.length; index++) {
  26115. if (this.cameras[index].id === id) {
  26116. return this.cameras[index];
  26117. }
  26118. }
  26119. return null;
  26120. };
  26121. /**
  26122. * Gets a camera using its unique id
  26123. * @param uniqueId defines the unique id to look for
  26124. * @returns the camera or null if not found
  26125. */
  26126. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26127. for (var index = 0; index < this.cameras.length; index++) {
  26128. if (this.cameras[index].uniqueId === uniqueId) {
  26129. return this.cameras[index];
  26130. }
  26131. }
  26132. return null;
  26133. };
  26134. /**
  26135. * Gets a camera using its name
  26136. * @param name defines the camera's name
  26137. * @return the camera or null if none found.
  26138. */
  26139. Scene.prototype.getCameraByName = function (name) {
  26140. for (var index = 0; index < this.cameras.length; index++) {
  26141. if (this.cameras[index].name === name) {
  26142. return this.cameras[index];
  26143. }
  26144. }
  26145. return null;
  26146. };
  26147. /**
  26148. * Gets a bone using its id
  26149. * @param id defines the bone's id
  26150. * @return the bone or null if not found
  26151. */
  26152. Scene.prototype.getBoneByID = function (id) {
  26153. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26154. var skeleton = this.skeletons[skeletonIndex];
  26155. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26156. if (skeleton.bones[boneIndex].id === id) {
  26157. return skeleton.bones[boneIndex];
  26158. }
  26159. }
  26160. }
  26161. return null;
  26162. };
  26163. /**
  26164. * Gets a bone using its id
  26165. * @param name defines the bone's name
  26166. * @return the bone or null if not found
  26167. */
  26168. Scene.prototype.getBoneByName = function (name) {
  26169. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26170. var skeleton = this.skeletons[skeletonIndex];
  26171. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26172. if (skeleton.bones[boneIndex].name === name) {
  26173. return skeleton.bones[boneIndex];
  26174. }
  26175. }
  26176. }
  26177. return null;
  26178. };
  26179. /**
  26180. * Gets a light node using its name
  26181. * @param name defines the the light's name
  26182. * @return the light or null if none found.
  26183. */
  26184. Scene.prototype.getLightByName = function (name) {
  26185. for (var index = 0; index < this.lights.length; index++) {
  26186. if (this.lights[index].name === name) {
  26187. return this.lights[index];
  26188. }
  26189. }
  26190. return null;
  26191. };
  26192. /**
  26193. * Gets a light node using its id
  26194. * @param id defines the light's id
  26195. * @return the light or null if none found.
  26196. */
  26197. Scene.prototype.getLightByID = function (id) {
  26198. for (var index = 0; index < this.lights.length; index++) {
  26199. if (this.lights[index].id === id) {
  26200. return this.lights[index];
  26201. }
  26202. }
  26203. return null;
  26204. };
  26205. /**
  26206. * Gets a light node using its scene-generated unique ID
  26207. * @param uniqueId defines the light's unique id
  26208. * @return the light or null if none found.
  26209. */
  26210. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26211. for (var index = 0; index < this.lights.length; index++) {
  26212. if (this.lights[index].uniqueId === uniqueId) {
  26213. return this.lights[index];
  26214. }
  26215. }
  26216. return null;
  26217. };
  26218. /**
  26219. * Gets a particle system by id
  26220. * @param id defines the particle system id
  26221. * @return the corresponding system or null if none found
  26222. */
  26223. Scene.prototype.getParticleSystemByID = function (id) {
  26224. for (var index = 0; index < this.particleSystems.length; index++) {
  26225. if (this.particleSystems[index].id === id) {
  26226. return this.particleSystems[index];
  26227. }
  26228. }
  26229. return null;
  26230. };
  26231. /**
  26232. * Gets a geometry using its ID
  26233. * @param id defines the geometry's id
  26234. * @return the geometry or null if none found.
  26235. */
  26236. Scene.prototype.getGeometryByID = function (id) {
  26237. for (var index = 0; index < this._geometries.length; index++) {
  26238. if (this._geometries[index].id === id) {
  26239. return this._geometries[index];
  26240. }
  26241. }
  26242. return null;
  26243. };
  26244. /**
  26245. * Add a new geometry to this scene
  26246. * @param geometry defines the geometry to be added to the scene.
  26247. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26248. * @return a boolean defining if the geometry was added or not
  26249. */
  26250. Scene.prototype.pushGeometry = function (geometry, force) {
  26251. if (!force && this.getGeometryByID(geometry.id)) {
  26252. return false;
  26253. }
  26254. this._geometries.push(geometry);
  26255. //notify the collision coordinator
  26256. if (this.collisionCoordinator) {
  26257. this.collisionCoordinator.onGeometryAdded(geometry);
  26258. }
  26259. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26260. return true;
  26261. };
  26262. /**
  26263. * Removes an existing geometry
  26264. * @param geometry defines the geometry to be removed from the scene
  26265. * @return a boolean defining if the geometry was removed or not
  26266. */
  26267. Scene.prototype.removeGeometry = function (geometry) {
  26268. var index = this._geometries.indexOf(geometry);
  26269. if (index > -1) {
  26270. this._geometries.splice(index, 1);
  26271. //notify the collision coordinator
  26272. if (this.collisionCoordinator) {
  26273. this.collisionCoordinator.onGeometryDeleted(geometry);
  26274. }
  26275. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26276. return true;
  26277. }
  26278. return false;
  26279. };
  26280. /**
  26281. * Gets the list of geometries attached to the scene
  26282. * @returns an array of Geometry
  26283. */
  26284. Scene.prototype.getGeometries = function () {
  26285. return this._geometries;
  26286. };
  26287. /**
  26288. * Gets the first added mesh found of a given ID
  26289. * @param id defines the id to search for
  26290. * @return the mesh found or null if not found at all
  26291. */
  26292. Scene.prototype.getMeshByID = function (id) {
  26293. for (var index = 0; index < this.meshes.length; index++) {
  26294. if (this.meshes[index].id === id) {
  26295. return this.meshes[index];
  26296. }
  26297. }
  26298. return null;
  26299. };
  26300. /**
  26301. * Gets a list of meshes using their id
  26302. * @param id defines the id to search for
  26303. * @returns a list of meshes
  26304. */
  26305. Scene.prototype.getMeshesByID = function (id) {
  26306. return this.meshes.filter(function (m) {
  26307. return m.id === id;
  26308. });
  26309. };
  26310. /**
  26311. * Gets the first added transform node found of a given ID
  26312. * @param id defines the id to search for
  26313. * @return the found transform node or null if not found at all.
  26314. */
  26315. Scene.prototype.getTransformNodeByID = function (id) {
  26316. for (var index = 0; index < this.transformNodes.length; index++) {
  26317. if (this.transformNodes[index].id === id) {
  26318. return this.transformNodes[index];
  26319. }
  26320. }
  26321. return null;
  26322. };
  26323. /**
  26324. * Gets a list of transform nodes using their id
  26325. * @param id defines the id to search for
  26326. * @returns a list of transform nodes
  26327. */
  26328. Scene.prototype.getTransformNodesByID = function (id) {
  26329. return this.transformNodes.filter(function (m) {
  26330. return m.id === id;
  26331. });
  26332. };
  26333. /**
  26334. * Gets a mesh with its auto-generated unique id
  26335. * @param uniqueId defines the unique id to search for
  26336. * @return the found mesh or null if not found at all.
  26337. */
  26338. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26339. for (var index = 0; index < this.meshes.length; index++) {
  26340. if (this.meshes[index].uniqueId === uniqueId) {
  26341. return this.meshes[index];
  26342. }
  26343. }
  26344. return null;
  26345. };
  26346. /**
  26347. * Gets a the last added mesh using a given id
  26348. * @param id defines the id to search for
  26349. * @return the found mesh or null if not found at all.
  26350. */
  26351. Scene.prototype.getLastMeshByID = function (id) {
  26352. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26353. if (this.meshes[index].id === id) {
  26354. return this.meshes[index];
  26355. }
  26356. }
  26357. return null;
  26358. };
  26359. /**
  26360. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26361. * @param id defines the id to search for
  26362. * @return the found node or null if not found at all
  26363. */
  26364. Scene.prototype.getLastEntryByID = function (id) {
  26365. var index;
  26366. for (index = this.meshes.length - 1; index >= 0; index--) {
  26367. if (this.meshes[index].id === id) {
  26368. return this.meshes[index];
  26369. }
  26370. }
  26371. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26372. if (this.transformNodes[index].id === id) {
  26373. return this.transformNodes[index];
  26374. }
  26375. }
  26376. for (index = this.cameras.length - 1; index >= 0; index--) {
  26377. if (this.cameras[index].id === id) {
  26378. return this.cameras[index];
  26379. }
  26380. }
  26381. for (index = this.lights.length - 1; index >= 0; index--) {
  26382. if (this.lights[index].id === id) {
  26383. return this.lights[index];
  26384. }
  26385. }
  26386. return null;
  26387. };
  26388. /**
  26389. * Gets a node (Mesh, Camera, Light) using a given id
  26390. * @param id defines the id to search for
  26391. * @return the found node or null if not found at all
  26392. */
  26393. Scene.prototype.getNodeByID = function (id) {
  26394. var mesh = this.getMeshByID(id);
  26395. if (mesh) {
  26396. return mesh;
  26397. }
  26398. var light = this.getLightByID(id);
  26399. if (light) {
  26400. return light;
  26401. }
  26402. var camera = this.getCameraByID(id);
  26403. if (camera) {
  26404. return camera;
  26405. }
  26406. var bone = this.getBoneByID(id);
  26407. return bone;
  26408. };
  26409. /**
  26410. * Gets a node (Mesh, Camera, Light) using a given name
  26411. * @param name defines the name to search for
  26412. * @return the found node or null if not found at all.
  26413. */
  26414. Scene.prototype.getNodeByName = function (name) {
  26415. var mesh = this.getMeshByName(name);
  26416. if (mesh) {
  26417. return mesh;
  26418. }
  26419. var light = this.getLightByName(name);
  26420. if (light) {
  26421. return light;
  26422. }
  26423. var camera = this.getCameraByName(name);
  26424. if (camera) {
  26425. return camera;
  26426. }
  26427. var bone = this.getBoneByName(name);
  26428. return bone;
  26429. };
  26430. /**
  26431. * Gets a mesh using a given name
  26432. * @param name defines the name to search for
  26433. * @return the found mesh or null if not found at all.
  26434. */
  26435. Scene.prototype.getMeshByName = function (name) {
  26436. for (var index = 0; index < this.meshes.length; index++) {
  26437. if (this.meshes[index].name === name) {
  26438. return this.meshes[index];
  26439. }
  26440. }
  26441. return null;
  26442. };
  26443. /**
  26444. * Gets a transform node using a given name
  26445. * @param name defines the name to search for
  26446. * @return the found transform node or null if not found at all.
  26447. */
  26448. Scene.prototype.getTransformNodeByName = function (name) {
  26449. for (var index = 0; index < this.transformNodes.length; index++) {
  26450. if (this.transformNodes[index].name === name) {
  26451. return this.transformNodes[index];
  26452. }
  26453. }
  26454. return null;
  26455. };
  26456. /**
  26457. * Gets a sound using a given name
  26458. * @param name defines the name to search for
  26459. * @return the found sound or null if not found at all.
  26460. */
  26461. Scene.prototype.getSoundByName = function (name) {
  26462. var index;
  26463. if (BABYLON.AudioEngine) {
  26464. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26465. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26466. return this.mainSoundTrack.soundCollection[index];
  26467. }
  26468. }
  26469. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26470. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26471. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26472. return this.soundTracks[sdIndex].soundCollection[index];
  26473. }
  26474. }
  26475. }
  26476. }
  26477. return null;
  26478. };
  26479. /**
  26480. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26481. * @param id defines the id to search for
  26482. * @return the found skeleton or null if not found at all.
  26483. */
  26484. Scene.prototype.getLastSkeletonByID = function (id) {
  26485. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26486. if (this.skeletons[index].id === id) {
  26487. return this.skeletons[index];
  26488. }
  26489. }
  26490. return null;
  26491. };
  26492. /**
  26493. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26494. * @param id defines the id to search for
  26495. * @return the found skeleton or null if not found at all.
  26496. */
  26497. Scene.prototype.getSkeletonById = function (id) {
  26498. for (var index = 0; index < this.skeletons.length; index++) {
  26499. if (this.skeletons[index].id === id) {
  26500. return this.skeletons[index];
  26501. }
  26502. }
  26503. return null;
  26504. };
  26505. /**
  26506. * Gets a skeleton using a given name
  26507. * @param name defines the name to search for
  26508. * @return the found skeleton or null if not found at all.
  26509. */
  26510. Scene.prototype.getSkeletonByName = function (name) {
  26511. for (var index = 0; index < this.skeletons.length; index++) {
  26512. if (this.skeletons[index].name === name) {
  26513. return this.skeletons[index];
  26514. }
  26515. }
  26516. return null;
  26517. };
  26518. /**
  26519. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26520. * @param id defines the id to search for
  26521. * @return the found morph target manager or null if not found at all.
  26522. */
  26523. Scene.prototype.getMorphTargetManagerById = function (id) {
  26524. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26525. if (this.morphTargetManagers[index].uniqueId === id) {
  26526. return this.morphTargetManagers[index];
  26527. }
  26528. }
  26529. return null;
  26530. };
  26531. /**
  26532. * Gets a boolean indicating if the given mesh is active
  26533. * @param mesh defines the mesh to look for
  26534. * @returns true if the mesh is in the active list
  26535. */
  26536. Scene.prototype.isActiveMesh = function (mesh) {
  26537. return (this._activeMeshes.indexOf(mesh) !== -1);
  26538. };
  26539. /**
  26540. * Return a the first highlight layer of the scene with a given name.
  26541. * @param name The name of the highlight layer to look for.
  26542. * @return The highlight layer if found otherwise null.
  26543. */
  26544. Scene.prototype.getHighlightLayerByName = function (name) {
  26545. for (var index = 0; index < this.effectLayers.length; index++) {
  26546. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26547. return this.effectLayers[index];
  26548. }
  26549. }
  26550. return null;
  26551. };
  26552. /**
  26553. * Return a the first highlight layer of the scene with a given name.
  26554. * @param name The name of the highlight layer to look for.
  26555. * @return The highlight layer if found otherwise null.
  26556. */
  26557. Scene.prototype.getGlowLayerByName = function (name) {
  26558. for (var index = 0; index < this.effectLayers.length; index++) {
  26559. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26560. return this.effectLayers[index];
  26561. }
  26562. }
  26563. return null;
  26564. };
  26565. Object.defineProperty(Scene.prototype, "uid", {
  26566. /**
  26567. * Return a unique id as a string which can serve as an identifier for the scene
  26568. */
  26569. get: function () {
  26570. if (!this._uid) {
  26571. this._uid = BABYLON.Tools.RandomId();
  26572. }
  26573. return this._uid;
  26574. },
  26575. enumerable: true,
  26576. configurable: true
  26577. });
  26578. /**
  26579. * Add an externaly attached data from its key.
  26580. * This method call will fail and return false, if such key already exists.
  26581. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26582. * @param key the unique key that identifies the data
  26583. * @param data the data object to associate to the key for this Engine instance
  26584. * @return true if no such key were already present and the data was added successfully, false otherwise
  26585. */
  26586. Scene.prototype.addExternalData = function (key, data) {
  26587. if (!this._externalData) {
  26588. this._externalData = new BABYLON.StringDictionary();
  26589. }
  26590. return this._externalData.add(key, data);
  26591. };
  26592. /**
  26593. * Get an externaly attached data from its key
  26594. * @param key the unique key that identifies the data
  26595. * @return the associated data, if present (can be null), or undefined if not present
  26596. */
  26597. Scene.prototype.getExternalData = function (key) {
  26598. if (!this._externalData) {
  26599. return null;
  26600. }
  26601. return this._externalData.get(key);
  26602. };
  26603. /**
  26604. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26605. * @param key the unique key that identifies the data
  26606. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26607. * @return the associated data, can be null if the factory returned null.
  26608. */
  26609. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26610. if (!this._externalData) {
  26611. this._externalData = new BABYLON.StringDictionary();
  26612. }
  26613. return this._externalData.getOrAddWithFactory(key, factory);
  26614. };
  26615. /**
  26616. * Remove an externaly attached data from the Engine instance
  26617. * @param key the unique key that identifies the data
  26618. * @return true if the data was successfully removed, false if it doesn't exist
  26619. */
  26620. Scene.prototype.removeExternalData = function (key) {
  26621. return this._externalData.remove(key);
  26622. };
  26623. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26624. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26625. if (mesh.showSubMeshesBoundingBox) {
  26626. var boundingInfo = subMesh.getBoundingInfo();
  26627. if (boundingInfo !== null && boundingInfo !== undefined) {
  26628. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26629. }
  26630. }
  26631. var material = subMesh.getMaterial();
  26632. if (material !== null && material !== undefined) {
  26633. // Render targets
  26634. if (material.getRenderTargetTextures !== undefined) {
  26635. if (this._processedMaterials.indexOf(material) === -1) {
  26636. this._processedMaterials.push(material);
  26637. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26638. }
  26639. }
  26640. // Dispatch
  26641. this._activeIndices.addCount(subMesh.indexCount, false);
  26642. this._renderingManager.dispatch(subMesh, mesh, material);
  26643. }
  26644. }
  26645. };
  26646. /**
  26647. * Clear the processed materials smart array preventing retention point in material dispose.
  26648. */
  26649. Scene.prototype.freeProcessedMaterials = function () {
  26650. this._processedMaterials.dispose();
  26651. };
  26652. /**
  26653. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26654. */
  26655. Scene.prototype.freeActiveMeshes = function () {
  26656. this._activeMeshes.dispose();
  26657. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26658. this.activeCamera._activeMeshes.dispose();
  26659. }
  26660. if (this.activeCameras) {
  26661. for (var i = 0; i < this.activeCameras.length; i++) {
  26662. var activeCamera = this.activeCameras[i];
  26663. if (activeCamera && activeCamera._activeMeshes) {
  26664. activeCamera._activeMeshes.dispose();
  26665. }
  26666. }
  26667. }
  26668. };
  26669. /**
  26670. * Clear the info related to rendering groups preventing retention points during dispose.
  26671. */
  26672. Scene.prototype.freeRenderingGroups = function () {
  26673. if (this._renderingManager) {
  26674. this._renderingManager.freeRenderingGroups();
  26675. }
  26676. if (this.textures) {
  26677. for (var i = 0; i < this.textures.length; i++) {
  26678. var texture = this.textures[i];
  26679. if (texture && texture.renderList) {
  26680. texture.freeRenderingGroups();
  26681. }
  26682. }
  26683. }
  26684. };
  26685. /** @ignore */
  26686. Scene.prototype._isInIntermediateRendering = function () {
  26687. return this._intermediateRendering;
  26688. };
  26689. /**
  26690. * Defines the current active mesh candidate provider
  26691. * @param provider defines the provider to use
  26692. */
  26693. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26694. this._activeMeshCandidateProvider = provider;
  26695. };
  26696. /**
  26697. * Gets the current active mesh candidate provider
  26698. * @returns the current active mesh candidate provider
  26699. */
  26700. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26701. return this._activeMeshCandidateProvider;
  26702. };
  26703. /**
  26704. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26705. * @returns the current scene
  26706. */
  26707. Scene.prototype.freezeActiveMeshes = function () {
  26708. if (!this.activeCamera) {
  26709. return this;
  26710. }
  26711. if (!this._frustumPlanes) {
  26712. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26713. }
  26714. this._evaluateActiveMeshes();
  26715. this._activeMeshesFrozen = true;
  26716. return this;
  26717. };
  26718. /**
  26719. * Use this function to restart evaluating active meshes on every frame
  26720. * @returns the current scene
  26721. */
  26722. Scene.prototype.unfreezeActiveMeshes = function () {
  26723. this._activeMeshesFrozen = false;
  26724. return this;
  26725. };
  26726. Scene.prototype._evaluateActiveMeshes = function () {
  26727. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26728. return;
  26729. }
  26730. if (!this.activeCamera) {
  26731. return;
  26732. }
  26733. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26734. this.activeCamera._activeMeshes.reset();
  26735. this._activeMeshes.reset();
  26736. this._renderingManager.reset();
  26737. this._processedMaterials.reset();
  26738. this._activeParticleSystems.reset();
  26739. this._activeSkeletons.reset();
  26740. this._softwareSkinnedMeshes.reset();
  26741. if (this._boundingBoxRenderer) {
  26742. this._boundingBoxRenderer.reset();
  26743. }
  26744. // Meshes
  26745. var meshes;
  26746. var len;
  26747. var checkIsEnabled = true;
  26748. // Determine mesh candidates
  26749. if (this._activeMeshCandidateProvider !== undefined) {
  26750. // Use _activeMeshCandidateProvider
  26751. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26752. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26753. if (meshes !== undefined) {
  26754. len = meshes.length;
  26755. }
  26756. else {
  26757. len = 0;
  26758. }
  26759. }
  26760. else if (this._selectionOctree !== undefined) {
  26761. // Octree
  26762. var selection = this._selectionOctree.select(this._frustumPlanes);
  26763. meshes = selection.data;
  26764. len = selection.length;
  26765. }
  26766. else {
  26767. // Full scene traversal
  26768. len = this.meshes.length;
  26769. meshes = this.meshes;
  26770. }
  26771. // Check each mesh
  26772. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26773. mesh = meshes[meshIndex];
  26774. if (mesh.isBlocked) {
  26775. continue;
  26776. }
  26777. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26778. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26779. continue;
  26780. }
  26781. mesh.computeWorldMatrix();
  26782. // Intersections
  26783. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26784. this._meshesForIntersections.pushNoDuplicate(mesh);
  26785. }
  26786. // Switch to current LOD
  26787. meshLOD = mesh.getLOD(this.activeCamera);
  26788. if (meshLOD === undefined || meshLOD === null) {
  26789. continue;
  26790. }
  26791. mesh._preActivate();
  26792. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26793. this._activeMeshes.push(mesh);
  26794. this.activeCamera._activeMeshes.push(mesh);
  26795. mesh._activate(this._renderId);
  26796. if (meshLOD !== mesh) {
  26797. meshLOD._activate(this._renderId);
  26798. }
  26799. this._activeMesh(mesh, meshLOD);
  26800. }
  26801. }
  26802. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26803. // Particle systems
  26804. if (this.particlesEnabled) {
  26805. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26806. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26807. var particleSystem = this.particleSystems[particleIndex];
  26808. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26809. continue;
  26810. }
  26811. var emitter = particleSystem.emitter;
  26812. if (!emitter.position || emitter.isEnabled()) {
  26813. this._activeParticleSystems.push(particleSystem);
  26814. particleSystem.animate();
  26815. this._renderingManager.dispatchParticles(particleSystem);
  26816. }
  26817. }
  26818. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26819. }
  26820. };
  26821. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26822. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26823. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26824. mesh.skeleton.prepare();
  26825. }
  26826. if (!mesh.computeBonesUsingShaders) {
  26827. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26828. }
  26829. }
  26830. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26831. var boundingInfo = sourceMesh.getBoundingInfo();
  26832. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26833. }
  26834. if (mesh !== undefined && mesh !== null
  26835. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26836. // Submeshes Octrees
  26837. var len;
  26838. var subMeshes;
  26839. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26840. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26841. len = intersections.length;
  26842. subMeshes = intersections.data;
  26843. }
  26844. else {
  26845. subMeshes = mesh.subMeshes;
  26846. len = subMeshes.length;
  26847. }
  26848. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26849. subMesh = subMeshes[subIndex];
  26850. this._evaluateSubMesh(subMesh, mesh);
  26851. }
  26852. }
  26853. };
  26854. /**
  26855. * Update the transform matrix to update from the current active camera
  26856. * @param force defines a boolean used to force the update even if cache is up to date
  26857. */
  26858. Scene.prototype.updateTransformMatrix = function (force) {
  26859. if (!this.activeCamera) {
  26860. return;
  26861. }
  26862. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26863. };
  26864. /**
  26865. * 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)
  26866. * @param alternateCamera defines the camera to use
  26867. */
  26868. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26869. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26870. };
  26871. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26872. if (camera && camera._skipRendering) {
  26873. return;
  26874. }
  26875. var engine = this._engine;
  26876. this.activeCamera = camera;
  26877. if (!this.activeCamera)
  26878. throw new Error("Active camera not set");
  26879. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26880. // Viewport
  26881. engine.setViewport(this.activeCamera.viewport);
  26882. // Camera
  26883. this.resetCachedMaterial();
  26884. this._renderId++;
  26885. this.updateTransformMatrix();
  26886. if (camera._alternateCamera) {
  26887. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26888. this._alternateRendering = true;
  26889. }
  26890. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26891. // Meshes
  26892. this._evaluateActiveMeshes();
  26893. // Software skinning
  26894. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26895. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26896. mesh.applySkeleton(mesh.skeleton);
  26897. }
  26898. // Render targets
  26899. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26900. var needsRestoreFrameBuffer = false;
  26901. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26902. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26903. }
  26904. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26905. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26906. }
  26907. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26908. this._intermediateRendering = true;
  26909. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26910. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26911. var renderTarget = this._renderTargets.data[renderIndex];
  26912. if (renderTarget._shouldRender()) {
  26913. this._renderId++;
  26914. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26915. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26916. }
  26917. }
  26918. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26919. this._intermediateRendering = false;
  26920. this._renderId++;
  26921. needsRestoreFrameBuffer = true; // Restore back buffer
  26922. }
  26923. // Render EffecttLayer Texture
  26924. var stencilState = this._engine.getStencilBuffer();
  26925. var renderEffects = false;
  26926. var needStencil = false;
  26927. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26928. this._intermediateRendering = true;
  26929. for (var i = 0; i < this.effectLayers.length; i++) {
  26930. var effectLayer = this.effectLayers[i];
  26931. if (effectLayer.shouldRender() &&
  26932. (!effectLayer.camera ||
  26933. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26934. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26935. renderEffects = true;
  26936. needStencil = needStencil || effectLayer.needStencil();
  26937. var renderTarget = effectLayer._mainTexture;
  26938. if (renderTarget._shouldRender()) {
  26939. this._renderId++;
  26940. renderTarget.render(false, false);
  26941. needsRestoreFrameBuffer = true;
  26942. }
  26943. }
  26944. }
  26945. this._intermediateRendering = false;
  26946. this._renderId++;
  26947. }
  26948. if (needsRestoreFrameBuffer) {
  26949. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26950. }
  26951. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26952. // Prepare Frame
  26953. this.postProcessManager._prepareFrame();
  26954. // Backgrounds
  26955. var layerIndex;
  26956. var layer;
  26957. if (this.layers.length) {
  26958. engine.setDepthBuffer(false);
  26959. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26960. layer = this.layers[layerIndex];
  26961. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26962. layer.render();
  26963. }
  26964. }
  26965. engine.setDepthBuffer(true);
  26966. }
  26967. // Activate effect Layer stencil
  26968. if (needStencil) {
  26969. this._engine.setStencilBuffer(true);
  26970. }
  26971. // Render
  26972. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26973. this._renderingManager.render(null, null, true, true);
  26974. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26975. // Restore effect Layer stencil
  26976. if (needStencil) {
  26977. this._engine.setStencilBuffer(stencilState);
  26978. }
  26979. // Bounding boxes
  26980. if (this._boundingBoxRenderer) {
  26981. this._boundingBoxRenderer.render();
  26982. }
  26983. // Lens flares
  26984. if (this.lensFlaresEnabled) {
  26985. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26986. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26987. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26988. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26989. lensFlareSystem.render();
  26990. }
  26991. }
  26992. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26993. }
  26994. // Effect Layer
  26995. if (renderEffects) {
  26996. engine.setDepthBuffer(false);
  26997. for (var i = 0; i < this.effectLayers.length; i++) {
  26998. if (this.effectLayers[i].shouldRender()) {
  26999. this.effectLayers[i].render();
  27000. }
  27001. }
  27002. engine.setDepthBuffer(true);
  27003. }
  27004. // Foregrounds
  27005. if (this.layers.length) {
  27006. engine.setDepthBuffer(false);
  27007. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27008. layer = this.layers[layerIndex];
  27009. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27010. layer.render();
  27011. }
  27012. }
  27013. engine.setDepthBuffer(true);
  27014. }
  27015. // Finalize frame
  27016. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27017. // Reset some special arrays
  27018. this._renderTargets.reset();
  27019. this._alternateRendering = false;
  27020. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27021. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27022. };
  27023. Scene.prototype._processSubCameras = function (camera) {
  27024. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27025. this._renderForCamera(camera);
  27026. return;
  27027. }
  27028. // rig cameras
  27029. for (var index = 0; index < camera._rigCameras.length; index++) {
  27030. this._renderForCamera(camera._rigCameras[index], camera);
  27031. }
  27032. this.activeCamera = camera;
  27033. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27034. };
  27035. Scene.prototype._checkIntersections = function () {
  27036. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27037. var sourceMesh = this._meshesForIntersections.data[index];
  27038. if (!sourceMesh.actionManager) {
  27039. continue;
  27040. }
  27041. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27042. var action = sourceMesh.actionManager.actions[actionIndex];
  27043. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27044. var parameters = action.getTriggerParameter();
  27045. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27046. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27047. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27048. if (areIntersecting && currentIntersectionInProgress === -1) {
  27049. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27050. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27051. sourceMesh._intersectionsInProgress.push(otherMesh);
  27052. }
  27053. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27054. sourceMesh._intersectionsInProgress.push(otherMesh);
  27055. }
  27056. }
  27057. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27058. //They intersected, and now they don't.
  27059. //is this trigger an exit trigger? execute an event.
  27060. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27061. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27062. }
  27063. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27064. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27065. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27066. return otherMesh === parameterMesh;
  27067. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27068. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27069. }
  27070. }
  27071. }
  27072. }
  27073. }
  27074. };
  27075. /**
  27076. * Render the scene
  27077. */
  27078. Scene.prototype.render = function () {
  27079. if (this.isDisposed) {
  27080. return;
  27081. }
  27082. this._activeParticles.fetchNewFrame();
  27083. this._totalVertices.fetchNewFrame();
  27084. this._activeIndices.fetchNewFrame();
  27085. this._activeBones.fetchNewFrame();
  27086. this._meshesForIntersections.reset();
  27087. this.resetCachedMaterial();
  27088. this.onBeforeAnimationsObservable.notifyObservers(this);
  27089. // Actions
  27090. if (this.actionManager) {
  27091. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27092. }
  27093. //Simplification Queue
  27094. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27095. this.simplificationQueue.executeNext();
  27096. }
  27097. if (this._engine.isDeterministicLockStep()) {
  27098. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27099. var defaultFPS = (60.0 / 1000.0);
  27100. var defaultFrameTime = 1000 / 60; // frame time in MS
  27101. if (this._physicsEngine) {
  27102. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27103. }
  27104. var stepsTaken = 0;
  27105. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27106. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27107. internalSteps = Math.min(internalSteps, maxSubSteps);
  27108. do {
  27109. this.onBeforeStepObservable.notifyObservers(this);
  27110. // Animations
  27111. this._animationRatio = defaultFrameTime * defaultFPS;
  27112. this._animate();
  27113. this.onAfterAnimationsObservable.notifyObservers(this);
  27114. // Physics
  27115. if (this._physicsEngine) {
  27116. this.onBeforePhysicsObservable.notifyObservers(this);
  27117. this._physicsEngine._step(defaultFrameTime / 1000);
  27118. this.onAfterPhysicsObservable.notifyObservers(this);
  27119. }
  27120. this.onAfterStepObservable.notifyObservers(this);
  27121. this._currentStepId++;
  27122. stepsTaken++;
  27123. deltaTime -= defaultFrameTime;
  27124. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27125. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27126. }
  27127. else {
  27128. // Animations
  27129. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27130. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27131. this._animate();
  27132. this.onAfterAnimationsObservable.notifyObservers(this);
  27133. // Physics
  27134. if (this._physicsEngine) {
  27135. this.onBeforePhysicsObservable.notifyObservers(this);
  27136. this._physicsEngine._step(deltaTime / 1000.0);
  27137. this.onAfterPhysicsObservable.notifyObservers(this);
  27138. }
  27139. }
  27140. // update gamepad manager
  27141. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27142. this._gamepadManager._checkGamepadsStatus();
  27143. }
  27144. // Update Cameras
  27145. if (this.activeCameras.length > 0) {
  27146. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27147. var camera = this.activeCameras[cameraIndex];
  27148. camera.update();
  27149. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27150. // rig cameras
  27151. for (var index = 0; index < camera._rigCameras.length; index++) {
  27152. camera._rigCameras[index].update();
  27153. }
  27154. }
  27155. }
  27156. }
  27157. else if (this.activeCamera) {
  27158. this.activeCamera.update();
  27159. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27160. // rig cameras
  27161. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27162. this.activeCamera._rigCameras[index].update();
  27163. }
  27164. }
  27165. }
  27166. // Before render
  27167. this.onBeforeRenderObservable.notifyObservers(this);
  27168. // Customs render targets
  27169. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27170. var engine = this.getEngine();
  27171. var currentActiveCamera = this.activeCamera;
  27172. if (this.renderTargetsEnabled) {
  27173. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27174. this._intermediateRendering = true;
  27175. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27176. var renderTarget = this.customRenderTargets[customIndex];
  27177. if (renderTarget._shouldRender()) {
  27178. this._renderId++;
  27179. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27180. if (!this.activeCamera)
  27181. throw new Error("Active camera not set");
  27182. // Viewport
  27183. engine.setViewport(this.activeCamera.viewport);
  27184. // Camera
  27185. this.updateTransformMatrix();
  27186. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27187. }
  27188. }
  27189. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27190. this._intermediateRendering = false;
  27191. this._renderId++;
  27192. }
  27193. // Restore back buffer
  27194. if (this.customRenderTargets.length > 0) {
  27195. engine.restoreDefaultFramebuffer();
  27196. }
  27197. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27198. this.activeCamera = currentActiveCamera;
  27199. // Procedural textures
  27200. if (this.proceduralTexturesEnabled) {
  27201. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27202. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27203. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27204. if (proceduralTexture._shouldRender()) {
  27205. proceduralTexture.render();
  27206. }
  27207. }
  27208. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27209. }
  27210. // Clear
  27211. if (this.autoClearDepthAndStencil || this.autoClear) {
  27212. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27213. }
  27214. // Shadows
  27215. if (this.shadowsEnabled) {
  27216. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27217. var light = this.lights[lightIndex];
  27218. var shadowGenerator = light.getShadowGenerator();
  27219. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27220. var shadowMap = (shadowGenerator.getShadowMap());
  27221. if (this.textures.indexOf(shadowMap) !== -1) {
  27222. this._renderTargets.push(shadowMap);
  27223. }
  27224. }
  27225. }
  27226. }
  27227. // Depth renderer
  27228. for (var key in this._depthRenderer) {
  27229. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27230. }
  27231. // Geometry renderer
  27232. if (this._geometryBufferRenderer) {
  27233. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27234. }
  27235. // RenderPipeline
  27236. if (this._postProcessRenderPipelineManager) {
  27237. this._postProcessRenderPipelineManager.update();
  27238. }
  27239. // Multi-cameras?
  27240. if (this.activeCameras.length > 0) {
  27241. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27242. if (cameraIndex > 0) {
  27243. this._engine.clear(null, false, true, true);
  27244. }
  27245. this._processSubCameras(this.activeCameras[cameraIndex]);
  27246. }
  27247. }
  27248. else {
  27249. if (!this.activeCamera) {
  27250. throw new Error("No camera defined");
  27251. }
  27252. this._processSubCameras(this.activeCamera);
  27253. }
  27254. // Intersection checks
  27255. this._checkIntersections();
  27256. // Update the audio listener attached to the camera
  27257. if (BABYLON.AudioEngine) {
  27258. this._updateAudioParameters();
  27259. }
  27260. // After render
  27261. if (this.afterRender) {
  27262. this.afterRender();
  27263. }
  27264. this.onAfterRenderObservable.notifyObservers(this);
  27265. // Cleaning
  27266. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27267. var data = this._toBeDisposed.data[index];
  27268. if (data) {
  27269. data.dispose();
  27270. }
  27271. this._toBeDisposed[index] = null;
  27272. }
  27273. this._toBeDisposed.reset();
  27274. if (this.dumpNextRenderTargets) {
  27275. this.dumpNextRenderTargets = false;
  27276. }
  27277. this._activeBones.addCount(0, true);
  27278. this._activeIndices.addCount(0, true);
  27279. this._activeParticles.addCount(0, true);
  27280. };
  27281. Scene.prototype._updateAudioParameters = function () {
  27282. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27283. return;
  27284. }
  27285. var listeningCamera;
  27286. var audioEngine = BABYLON.Engine.audioEngine;
  27287. if (this.activeCameras.length > 0) {
  27288. listeningCamera = this.activeCameras[0];
  27289. }
  27290. else {
  27291. listeningCamera = this.activeCamera;
  27292. }
  27293. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27294. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27295. // for VR cameras
  27296. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27297. listeningCamera = listeningCamera.rigCameras[0];
  27298. }
  27299. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27300. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27301. cameraDirection.normalize();
  27302. // To avoid some errors on GearVR
  27303. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27304. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27305. }
  27306. var i;
  27307. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27308. var sound = this.mainSoundTrack.soundCollection[i];
  27309. if (sound.useCustomAttenuation) {
  27310. sound.updateDistanceFromListener();
  27311. }
  27312. }
  27313. for (i = 0; i < this.soundTracks.length; i++) {
  27314. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27315. sound = this.soundTracks[i].soundCollection[j];
  27316. if (sound.useCustomAttenuation) {
  27317. sound.updateDistanceFromListener();
  27318. }
  27319. }
  27320. }
  27321. }
  27322. };
  27323. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27324. // Audio
  27325. /**
  27326. * Gets or sets if audio support is enabled
  27327. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27328. */
  27329. get: function () {
  27330. return this._audioEnabled;
  27331. },
  27332. set: function (value) {
  27333. this._audioEnabled = value;
  27334. if (BABYLON.AudioEngine) {
  27335. if (this._audioEnabled) {
  27336. this._enableAudio();
  27337. }
  27338. else {
  27339. this._disableAudio();
  27340. }
  27341. }
  27342. },
  27343. enumerable: true,
  27344. configurable: true
  27345. });
  27346. Scene.prototype._disableAudio = function () {
  27347. var i;
  27348. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27349. this.mainSoundTrack.soundCollection[i].pause();
  27350. }
  27351. for (i = 0; i < this.soundTracks.length; i++) {
  27352. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27353. this.soundTracks[i].soundCollection[j].pause();
  27354. }
  27355. }
  27356. };
  27357. Scene.prototype._enableAudio = function () {
  27358. var i;
  27359. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27360. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27361. this.mainSoundTrack.soundCollection[i].play();
  27362. }
  27363. }
  27364. for (i = 0; i < this.soundTracks.length; i++) {
  27365. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27366. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27367. this.soundTracks[i].soundCollection[j].play();
  27368. }
  27369. }
  27370. }
  27371. };
  27372. Object.defineProperty(Scene.prototype, "headphone", {
  27373. /**
  27374. * Gets or sets if audio will be output to headphones
  27375. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27376. */
  27377. get: function () {
  27378. return this._headphone;
  27379. },
  27380. set: function (value) {
  27381. this._headphone = value;
  27382. if (BABYLON.AudioEngine) {
  27383. if (this._headphone) {
  27384. this._switchAudioModeForHeadphones();
  27385. }
  27386. else {
  27387. this._switchAudioModeForNormalSpeakers();
  27388. }
  27389. }
  27390. },
  27391. enumerable: true,
  27392. configurable: true
  27393. });
  27394. Scene.prototype._switchAudioModeForHeadphones = function () {
  27395. this.mainSoundTrack.switchPanningModelToHRTF();
  27396. for (var i = 0; i < this.soundTracks.length; i++) {
  27397. this.soundTracks[i].switchPanningModelToHRTF();
  27398. }
  27399. };
  27400. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27401. this.mainSoundTrack.switchPanningModelToEqualPower();
  27402. for (var i = 0; i < this.soundTracks.length; i++) {
  27403. this.soundTracks[i].switchPanningModelToEqualPower();
  27404. }
  27405. };
  27406. /**
  27407. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27408. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27409. * @returns the created depth renderer
  27410. */
  27411. Scene.prototype.enableDepthRenderer = function (camera) {
  27412. camera = camera || this.activeCamera;
  27413. if (!camera) {
  27414. throw "No camera available to enable depth renderer";
  27415. }
  27416. if (!this._depthRenderer[camera.id]) {
  27417. var textureType = 0;
  27418. if (this._engine.getCaps().textureHalfFloatRender) {
  27419. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27420. }
  27421. else if (this._engine.getCaps().textureFloatRender) {
  27422. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27423. }
  27424. else {
  27425. throw "Depth renderer does not support int texture type";
  27426. }
  27427. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27428. }
  27429. return this._depthRenderer[camera.id];
  27430. };
  27431. /**
  27432. * Disables a depth renderer for a given camera
  27433. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27434. */
  27435. Scene.prototype.disableDepthRenderer = function (camera) {
  27436. camera = camera || this.activeCamera;
  27437. if (!camera || !this._depthRenderer[camera.id]) {
  27438. return;
  27439. }
  27440. this._depthRenderer[camera.id].dispose();
  27441. delete this._depthRenderer[camera.id];
  27442. };
  27443. /**
  27444. * Enables a GeometryBufferRender and associates it with the scene
  27445. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27446. * @returns the GeometryBufferRenderer
  27447. */
  27448. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27449. if (ratio === void 0) { ratio = 1; }
  27450. if (this._geometryBufferRenderer) {
  27451. return this._geometryBufferRenderer;
  27452. }
  27453. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27454. if (!this._geometryBufferRenderer.isSupported) {
  27455. this._geometryBufferRenderer = null;
  27456. }
  27457. return this._geometryBufferRenderer;
  27458. };
  27459. /**
  27460. * Disables the GeometryBufferRender associated with the scene
  27461. */
  27462. Scene.prototype.disableGeometryBufferRenderer = function () {
  27463. if (!this._geometryBufferRenderer) {
  27464. return;
  27465. }
  27466. this._geometryBufferRenderer.dispose();
  27467. this._geometryBufferRenderer = null;
  27468. };
  27469. /**
  27470. * Freeze all materials
  27471. * A frozen material will not be updatable but should be faster to render
  27472. */
  27473. Scene.prototype.freezeMaterials = function () {
  27474. for (var i = 0; i < this.materials.length; i++) {
  27475. this.materials[i].freeze();
  27476. }
  27477. };
  27478. /**
  27479. * Unfreeze all materials
  27480. * A frozen material will not be updatable but should be faster to render
  27481. */
  27482. Scene.prototype.unfreezeMaterials = function () {
  27483. for (var i = 0; i < this.materials.length; i++) {
  27484. this.materials[i].unfreeze();
  27485. }
  27486. };
  27487. /**
  27488. * Releases all held ressources
  27489. */
  27490. Scene.prototype.dispose = function () {
  27491. this.beforeRender = null;
  27492. this.afterRender = null;
  27493. this.skeletons = [];
  27494. this.morphTargetManagers = [];
  27495. this.importedMeshesFiles = new Array();
  27496. this.stopAllAnimations();
  27497. this.resetCachedMaterial();
  27498. for (var key in this._depthRenderer) {
  27499. this._depthRenderer[key].dispose();
  27500. }
  27501. if (this._gamepadManager) {
  27502. this._gamepadManager.dispose();
  27503. this._gamepadManager = null;
  27504. }
  27505. // Smart arrays
  27506. if (this.activeCamera) {
  27507. this.activeCamera._activeMeshes.dispose();
  27508. this.activeCamera = null;
  27509. }
  27510. this._activeMeshes.dispose();
  27511. this._renderingManager.dispose();
  27512. this._processedMaterials.dispose();
  27513. this._activeParticleSystems.dispose();
  27514. this._activeSkeletons.dispose();
  27515. this._softwareSkinnedMeshes.dispose();
  27516. this._renderTargets.dispose();
  27517. this._registeredForLateAnimationBindings.dispose();
  27518. if (this._boundingBoxRenderer) {
  27519. this._boundingBoxRenderer.dispose();
  27520. }
  27521. this._meshesForIntersections.dispose();
  27522. this._toBeDisposed.dispose();
  27523. // Abort active requests
  27524. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27525. var request = _a[_i];
  27526. request.abort();
  27527. }
  27528. // Debug layer
  27529. if (this._debugLayer) {
  27530. this._debugLayer.hide();
  27531. }
  27532. // Events
  27533. this.onDisposeObservable.notifyObservers(this);
  27534. this.onDisposeObservable.clear();
  27535. this.onBeforeRenderObservable.clear();
  27536. this.onAfterRenderObservable.clear();
  27537. this.onBeforeRenderTargetsRenderObservable.clear();
  27538. this.onAfterRenderTargetsRenderObservable.clear();
  27539. this.onAfterStepObservable.clear();
  27540. this.onBeforeStepObservable.clear();
  27541. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27542. this.onAfterActiveMeshesEvaluationObservable.clear();
  27543. this.onBeforeParticlesRenderingObservable.clear();
  27544. this.onAfterParticlesRenderingObservable.clear();
  27545. this.onBeforeSpritesRenderingObservable.clear();
  27546. this.onAfterSpritesRenderingObservable.clear();
  27547. this.onBeforeDrawPhaseObservable.clear();
  27548. this.onAfterDrawPhaseObservable.clear();
  27549. this.onBeforePhysicsObservable.clear();
  27550. this.onAfterPhysicsObservable.clear();
  27551. this.onBeforeAnimationsObservable.clear();
  27552. this.onAfterAnimationsObservable.clear();
  27553. this.onDataLoadedObservable.clear();
  27554. this.detachControl();
  27555. // Release sounds & sounds tracks
  27556. if (BABYLON.AudioEngine) {
  27557. this.disposeSounds();
  27558. }
  27559. // VR Helper
  27560. if (this.VRHelper) {
  27561. this.VRHelper.dispose();
  27562. }
  27563. // Detach cameras
  27564. var canvas = this._engine.getRenderingCanvas();
  27565. if (canvas) {
  27566. var index;
  27567. for (index = 0; index < this.cameras.length; index++) {
  27568. this.cameras[index].detachControl(canvas);
  27569. }
  27570. }
  27571. // Release animation groups
  27572. while (this.animationGroups.length) {
  27573. this.animationGroups[0].dispose();
  27574. }
  27575. // Release lights
  27576. while (this.lights.length) {
  27577. this.lights[0].dispose();
  27578. }
  27579. // Release meshes
  27580. while (this.meshes.length) {
  27581. this.meshes[0].dispose(true);
  27582. }
  27583. while (this.transformNodes.length) {
  27584. this.removeTransformNode(this.transformNodes[0]);
  27585. }
  27586. // Release cameras
  27587. while (this.cameras.length) {
  27588. this.cameras[0].dispose();
  27589. }
  27590. // Release materials
  27591. if (this.defaultMaterial) {
  27592. this.defaultMaterial.dispose();
  27593. }
  27594. while (this.multiMaterials.length) {
  27595. this.multiMaterials[0].dispose();
  27596. }
  27597. while (this.materials.length) {
  27598. this.materials[0].dispose();
  27599. }
  27600. // Release particles
  27601. while (this.particleSystems.length) {
  27602. this.particleSystems[0].dispose();
  27603. }
  27604. // Release sprites
  27605. while (this.spriteManagers.length) {
  27606. this.spriteManagers[0].dispose();
  27607. }
  27608. // Release postProcesses
  27609. while (this.postProcesses.length) {
  27610. this.postProcesses[0].dispose();
  27611. }
  27612. // Release layers
  27613. while (this.layers.length) {
  27614. this.layers[0].dispose();
  27615. }
  27616. while (this.effectLayers.length) {
  27617. this.effectLayers[0].dispose();
  27618. }
  27619. // Release textures
  27620. while (this.textures.length) {
  27621. this.textures[0].dispose();
  27622. }
  27623. // Release UBO
  27624. this._sceneUbo.dispose();
  27625. if (this._alternateSceneUbo) {
  27626. this._alternateSceneUbo.dispose();
  27627. }
  27628. // Post-processes
  27629. this.postProcessManager.dispose();
  27630. if (this._postProcessRenderPipelineManager) {
  27631. this._postProcessRenderPipelineManager.dispose();
  27632. }
  27633. // Physics
  27634. if (this._physicsEngine) {
  27635. this.disablePhysicsEngine();
  27636. }
  27637. // Remove from engine
  27638. index = this._engine.scenes.indexOf(this);
  27639. if (index > -1) {
  27640. this._engine.scenes.splice(index, 1);
  27641. }
  27642. this._engine.wipeCaches(true);
  27643. this._isDisposed = true;
  27644. };
  27645. Object.defineProperty(Scene.prototype, "isDisposed", {
  27646. /**
  27647. * Gets if the scene is already disposed
  27648. */
  27649. get: function () {
  27650. return this._isDisposed;
  27651. },
  27652. enumerable: true,
  27653. configurable: true
  27654. });
  27655. /**
  27656. * Releases sounds & soundtracks
  27657. */
  27658. Scene.prototype.disposeSounds = function () {
  27659. if (!this._mainSoundTrack) {
  27660. return;
  27661. }
  27662. this.mainSoundTrack.dispose();
  27663. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27664. this.soundTracks[scIndex].dispose();
  27665. }
  27666. };
  27667. // Octrees
  27668. /**
  27669. * Get the world extend vectors with an optional filter
  27670. *
  27671. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27672. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27673. */
  27674. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27675. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27676. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27677. filterPredicate = filterPredicate || (function () { return true; });
  27678. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27679. mesh.computeWorldMatrix(true);
  27680. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27681. return;
  27682. }
  27683. var boundingInfo = mesh.getBoundingInfo();
  27684. var minBox = boundingInfo.boundingBox.minimumWorld;
  27685. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27686. BABYLON.Tools.CheckExtends(minBox, min, max);
  27687. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27688. });
  27689. return {
  27690. min: min,
  27691. max: max
  27692. };
  27693. };
  27694. /**
  27695. * Creates or updates the octree used to boost selection (picking)
  27696. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27697. * @param maxCapacity defines the maximum capacity per leaf
  27698. * @param maxDepth defines the maximum depth of the octree
  27699. * @returns an octree of AbstractMesh
  27700. */
  27701. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27702. if (maxCapacity === void 0) { maxCapacity = 64; }
  27703. if (maxDepth === void 0) { maxDepth = 2; }
  27704. if (!this._selectionOctree) {
  27705. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27706. }
  27707. var worldExtends = this.getWorldExtends();
  27708. // Update octree
  27709. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27710. return this._selectionOctree;
  27711. };
  27712. // Picking
  27713. /**
  27714. * Creates a ray that can be used to pick in the scene
  27715. * @param x defines the x coordinate of the origin (on-screen)
  27716. * @param y defines the y coordinate of the origin (on-screen)
  27717. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27718. * @param camera defines the camera to use for the picking
  27719. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27720. * @returns a Ray
  27721. */
  27722. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27723. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27724. var result = BABYLON.Ray.Zero();
  27725. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27726. return result;
  27727. };
  27728. /**
  27729. * Creates a ray that can be used to pick in the scene
  27730. * @param x defines the x coordinate of the origin (on-screen)
  27731. * @param y defines the y coordinate of the origin (on-screen)
  27732. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27733. * @param result defines the ray where to store the picking ray
  27734. * @param camera defines the camera to use for the picking
  27735. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27736. * @returns the current scene
  27737. */
  27738. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27739. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27740. var engine = this._engine;
  27741. if (!camera) {
  27742. if (!this.activeCamera)
  27743. throw new Error("Active camera not set");
  27744. camera = this.activeCamera;
  27745. }
  27746. var cameraViewport = camera.viewport;
  27747. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27748. // Moving coordinates to local viewport world
  27749. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27750. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27751. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27752. return this;
  27753. };
  27754. /**
  27755. * Creates a ray that can be used to pick in the scene
  27756. * @param x defines the x coordinate of the origin (on-screen)
  27757. * @param y defines the y coordinate of the origin (on-screen)
  27758. * @param camera defines the camera to use for the picking
  27759. * @returns a Ray
  27760. */
  27761. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27762. var result = BABYLON.Ray.Zero();
  27763. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27764. return result;
  27765. };
  27766. /**
  27767. * Creates a ray that can be used to pick in the scene
  27768. * @param x defines the x coordinate of the origin (on-screen)
  27769. * @param y defines the y coordinate of the origin (on-screen)
  27770. * @param result defines the ray where to store the picking ray
  27771. * @param camera defines the camera to use for the picking
  27772. * @returns the current scene
  27773. */
  27774. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27775. if (!BABYLON.PickingInfo) {
  27776. return this;
  27777. }
  27778. var engine = this._engine;
  27779. if (!camera) {
  27780. if (!this.activeCamera)
  27781. throw new Error("Active camera not set");
  27782. camera = this.activeCamera;
  27783. }
  27784. var cameraViewport = camera.viewport;
  27785. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27786. var identity = BABYLON.Matrix.Identity();
  27787. // Moving coordinates to local viewport world
  27788. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27789. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27790. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27791. return this;
  27792. };
  27793. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27794. if (!BABYLON.PickingInfo) {
  27795. return null;
  27796. }
  27797. var pickingInfo = null;
  27798. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27799. var mesh = this.meshes[meshIndex];
  27800. if (predicate) {
  27801. if (!predicate(mesh)) {
  27802. continue;
  27803. }
  27804. }
  27805. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27806. continue;
  27807. }
  27808. var world = mesh.getWorldMatrix();
  27809. var ray = rayFunction(world);
  27810. var result = mesh.intersects(ray, fastCheck);
  27811. if (!result || !result.hit)
  27812. continue;
  27813. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27814. continue;
  27815. pickingInfo = result;
  27816. if (fastCheck) {
  27817. break;
  27818. }
  27819. }
  27820. return pickingInfo || new BABYLON.PickingInfo();
  27821. };
  27822. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27823. if (!BABYLON.PickingInfo) {
  27824. return null;
  27825. }
  27826. var pickingInfos = new Array();
  27827. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27828. var mesh = this.meshes[meshIndex];
  27829. if (predicate) {
  27830. if (!predicate(mesh)) {
  27831. continue;
  27832. }
  27833. }
  27834. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27835. continue;
  27836. }
  27837. var world = mesh.getWorldMatrix();
  27838. var ray = rayFunction(world);
  27839. var result = mesh.intersects(ray, false);
  27840. if (!result || !result.hit)
  27841. continue;
  27842. pickingInfos.push(result);
  27843. }
  27844. return pickingInfos;
  27845. };
  27846. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27847. if (!BABYLON.PickingInfo) {
  27848. return null;
  27849. }
  27850. var pickingInfo = null;
  27851. if (!camera) {
  27852. if (!this.activeCamera) {
  27853. return null;
  27854. }
  27855. camera = this.activeCamera;
  27856. }
  27857. if (this.spriteManagers.length > 0) {
  27858. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27859. var spriteManager = this.spriteManagers[spriteIndex];
  27860. if (!spriteManager.isPickable) {
  27861. continue;
  27862. }
  27863. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27864. if (!result || !result.hit)
  27865. continue;
  27866. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27867. continue;
  27868. pickingInfo = result;
  27869. if (fastCheck) {
  27870. break;
  27871. }
  27872. }
  27873. }
  27874. return pickingInfo || new BABYLON.PickingInfo();
  27875. };
  27876. /** Launch a ray to try to pick a mesh in the scene
  27877. * @param x position on screen
  27878. * @param y position on screen
  27879. * @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
  27880. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27881. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27882. * @returns a PickingInfo
  27883. */
  27884. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27885. var _this = this;
  27886. if (!BABYLON.PickingInfo) {
  27887. return null;
  27888. }
  27889. return this._internalPick(function (world) {
  27890. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27891. return _this._tempPickingRay;
  27892. }, predicate, fastCheck);
  27893. };
  27894. /** Launch a ray to try to pick a sprite in the scene
  27895. * @param x position on screen
  27896. * @param y position on screen
  27897. * @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
  27898. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27899. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27900. * @returns a PickingInfo
  27901. */
  27902. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27903. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27904. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27905. };
  27906. /** Use the given ray to pick a mesh in the scene
  27907. * @param ray The ray to use to pick meshes
  27908. * @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
  27909. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27910. * @returns a PickingInfo
  27911. */
  27912. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27913. var _this = this;
  27914. return this._internalPick(function (world) {
  27915. if (!_this._pickWithRayInverseMatrix) {
  27916. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27917. }
  27918. world.invertToRef(_this._pickWithRayInverseMatrix);
  27919. if (!_this._cachedRayForTransform) {
  27920. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27921. }
  27922. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27923. return _this._cachedRayForTransform;
  27924. }, predicate, fastCheck);
  27925. };
  27926. /**
  27927. * Launch a ray to try to pick a mesh in the scene
  27928. * @param x X position on screen
  27929. * @param y Y position on screen
  27930. * @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
  27931. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27932. * @returns an array of PickingInfo
  27933. */
  27934. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27935. var _this = this;
  27936. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27937. };
  27938. /**
  27939. * Launch a ray to try to pick a mesh in the scene
  27940. * @param ray Ray to use
  27941. * @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
  27942. * @returns an array of PickingInfo
  27943. */
  27944. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27945. var _this = this;
  27946. return this._internalMultiPick(function (world) {
  27947. if (!_this._pickWithRayInverseMatrix) {
  27948. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27949. }
  27950. world.invertToRef(_this._pickWithRayInverseMatrix);
  27951. if (!_this._cachedRayForTransform) {
  27952. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27953. }
  27954. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27955. return _this._cachedRayForTransform;
  27956. }, predicate);
  27957. };
  27958. /**
  27959. * Force the value of meshUnderPointer
  27960. * @param mesh defines the mesh to use
  27961. */
  27962. Scene.prototype.setPointerOverMesh = function (mesh) {
  27963. if (this._pointerOverMesh === mesh) {
  27964. return;
  27965. }
  27966. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27967. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27968. }
  27969. this._pointerOverMesh = mesh;
  27970. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27971. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27972. }
  27973. };
  27974. /**
  27975. * Gets the mesh under the pointer
  27976. * @returns a Mesh or null if no mesh is under the pointer
  27977. */
  27978. Scene.prototype.getPointerOverMesh = function () {
  27979. return this._pointerOverMesh;
  27980. };
  27981. /**
  27982. * Force the sprite under the pointer
  27983. * @param sprite defines the sprite to use
  27984. */
  27985. Scene.prototype.setPointerOverSprite = function (sprite) {
  27986. if (this._pointerOverSprite === sprite) {
  27987. return;
  27988. }
  27989. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27990. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27991. }
  27992. this._pointerOverSprite = sprite;
  27993. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27994. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27995. }
  27996. };
  27997. /**
  27998. * Gets the sprite under the pointer
  27999. * @returns a Sprite or null if no sprite is under the pointer
  28000. */
  28001. Scene.prototype.getPointerOverSprite = function () {
  28002. return this._pointerOverSprite;
  28003. };
  28004. // Physics
  28005. /**
  28006. * Gets the current physics engine
  28007. * @returns a PhysicsEngine or null if none attached
  28008. */
  28009. Scene.prototype.getPhysicsEngine = function () {
  28010. return this._physicsEngine;
  28011. };
  28012. /**
  28013. * Enables physics to the current scene
  28014. * @param gravity defines the scene's gravity for the physics engine
  28015. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28016. * @return a boolean indicating if the physics engine was initialized
  28017. */
  28018. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28019. if (gravity === void 0) { gravity = null; }
  28020. if (this._physicsEngine) {
  28021. return true;
  28022. }
  28023. try {
  28024. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28025. return true;
  28026. }
  28027. catch (e) {
  28028. BABYLON.Tools.Error(e.message);
  28029. return false;
  28030. }
  28031. };
  28032. /**
  28033. * Disables and disposes the physics engine associated with the scene
  28034. */
  28035. Scene.prototype.disablePhysicsEngine = function () {
  28036. if (!this._physicsEngine) {
  28037. return;
  28038. }
  28039. this._physicsEngine.dispose();
  28040. this._physicsEngine = null;
  28041. };
  28042. /**
  28043. * Gets a boolean indicating if there is an active physics engine
  28044. * @returns a boolean indicating if there is an active physics engine
  28045. */
  28046. Scene.prototype.isPhysicsEnabled = function () {
  28047. return this._physicsEngine !== undefined;
  28048. };
  28049. /**
  28050. * Deletes a physics compound impostor
  28051. * @param compound defines the compound to delete
  28052. */
  28053. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28054. var mesh = compound.parts[0].mesh;
  28055. if (mesh.physicsImpostor) {
  28056. mesh.physicsImpostor.dispose();
  28057. mesh.physicsImpostor = null;
  28058. }
  28059. };
  28060. // Misc.
  28061. /** @ignore */
  28062. Scene.prototype._rebuildGeometries = function () {
  28063. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28064. var geometry = _a[_i];
  28065. geometry._rebuild();
  28066. }
  28067. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28068. var mesh = _c[_b];
  28069. mesh._rebuild();
  28070. }
  28071. if (this.postProcessManager) {
  28072. this.postProcessManager._rebuild();
  28073. }
  28074. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28075. var layer = _e[_d];
  28076. layer._rebuild();
  28077. }
  28078. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28079. var effectLayer = _g[_f];
  28080. effectLayer._rebuild();
  28081. }
  28082. if (this._boundingBoxRenderer) {
  28083. this._boundingBoxRenderer._rebuild();
  28084. }
  28085. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28086. var system = _j[_h];
  28087. system.rebuild();
  28088. }
  28089. if (this._postProcessRenderPipelineManager) {
  28090. this._postProcessRenderPipelineManager._rebuild();
  28091. }
  28092. };
  28093. /** @ignore */
  28094. Scene.prototype._rebuildTextures = function () {
  28095. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28096. var texture = _a[_i];
  28097. texture._rebuild();
  28098. }
  28099. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28100. };
  28101. /**
  28102. * Creates a default light for the scene.
  28103. * @param replace Whether to replace the existing lights in the scene.
  28104. */
  28105. Scene.prototype.createDefaultLight = function (replace) {
  28106. if (replace === void 0) { replace = false; }
  28107. // Dispose existing light in replace mode.
  28108. if (replace) {
  28109. if (this.lights) {
  28110. for (var i = 0; i < this.lights.length; i++) {
  28111. this.lights[i].dispose();
  28112. }
  28113. }
  28114. }
  28115. // Light
  28116. if (this.lights.length === 0) {
  28117. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28118. }
  28119. };
  28120. /**
  28121. * Creates a default camera for the scene.
  28122. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28123. * @param replace Whether to replace the existing active camera in the scene.
  28124. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28125. */
  28126. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28127. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28128. if (replace === void 0) { replace = false; }
  28129. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28130. // Dispose existing camera in replace mode.
  28131. if (replace) {
  28132. if (this.activeCamera) {
  28133. this.activeCamera.dispose();
  28134. this.activeCamera = null;
  28135. }
  28136. }
  28137. // Camera
  28138. if (!this.activeCamera) {
  28139. var worldExtends = this.getWorldExtends();
  28140. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28141. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28142. var camera;
  28143. var radius = worldSize.length() * 1.5;
  28144. // empty scene scenario!
  28145. if (!isFinite(radius)) {
  28146. radius = 1;
  28147. worldCenter.copyFromFloats(0, 0, 0);
  28148. }
  28149. if (createArcRotateCamera) {
  28150. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28151. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28152. arcRotateCamera.wheelPrecision = 100 / radius;
  28153. camera = arcRotateCamera;
  28154. }
  28155. else {
  28156. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28157. freeCamera.setTarget(worldCenter);
  28158. camera = freeCamera;
  28159. }
  28160. camera.minZ = radius * 0.01;
  28161. camera.maxZ = radius * 1000;
  28162. camera.speed = radius * 0.2;
  28163. this.activeCamera = camera;
  28164. var canvas = this.getEngine().getRenderingCanvas();
  28165. if (attachCameraControls && canvas) {
  28166. camera.attachControl(canvas);
  28167. }
  28168. }
  28169. };
  28170. /**
  28171. * Creates a default camera and a default light
  28172. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28173. * @param replace defines if the camera and/or light will replace the existing ones
  28174. * @param attachCameraControls defines if attachControl will be called on the new camera
  28175. */
  28176. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28177. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28178. if (replace === void 0) { replace = false; }
  28179. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28180. this.createDefaultLight(replace);
  28181. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28182. };
  28183. /**
  28184. * Creates a new sky box
  28185. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28186. * @param environmentTexture defines the texture to use as environment texture
  28187. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28188. * @param scale defines the overall scale of the skybox
  28189. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28190. * @returns a new mesh holding the sky box
  28191. */
  28192. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28193. if (pbr === void 0) { pbr = false; }
  28194. if (scale === void 0) { scale = 1000; }
  28195. if (blur === void 0) { blur = 0; }
  28196. if (environmentTexture) {
  28197. this.environmentTexture = environmentTexture;
  28198. }
  28199. if (!this.environmentTexture) {
  28200. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28201. return null;
  28202. }
  28203. // Skybox
  28204. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28205. if (pbr) {
  28206. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28207. hdrSkyboxMaterial.backFaceCulling = false;
  28208. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28209. if (hdrSkyboxMaterial.reflectionTexture) {
  28210. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28211. }
  28212. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28213. hdrSkyboxMaterial.disableLighting = true;
  28214. hdrSkyboxMaterial.twoSidedLighting = true;
  28215. hdrSkybox.infiniteDistance = true;
  28216. hdrSkybox.material = hdrSkyboxMaterial;
  28217. }
  28218. else {
  28219. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28220. skyboxMaterial.backFaceCulling = false;
  28221. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28222. if (skyboxMaterial.reflectionTexture) {
  28223. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28224. }
  28225. skyboxMaterial.disableLighting = true;
  28226. hdrSkybox.infiniteDistance = true;
  28227. hdrSkybox.material = skyboxMaterial;
  28228. }
  28229. return hdrSkybox;
  28230. };
  28231. /**
  28232. * Creates a new environment
  28233. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28234. * @param options defines the options you can use to configure the environment
  28235. * @returns the new EnvironmentHelper
  28236. */
  28237. Scene.prototype.createDefaultEnvironment = function (options) {
  28238. if (BABYLON.EnvironmentHelper) {
  28239. return new BABYLON.EnvironmentHelper(options, this);
  28240. }
  28241. return null;
  28242. };
  28243. /**
  28244. * Creates a new VREXperienceHelper
  28245. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28246. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28247. * @returns a new VREXperienceHelper
  28248. */
  28249. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28250. if (webVROptions === void 0) { webVROptions = {}; }
  28251. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28252. };
  28253. // Tags
  28254. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28255. if (tagsQuery === undefined) {
  28256. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28257. return list;
  28258. }
  28259. var listByTags = [];
  28260. forEach = forEach || (function (item) { return; });
  28261. for (var i in list) {
  28262. var item = list[i];
  28263. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28264. listByTags.push(item);
  28265. forEach(item);
  28266. }
  28267. }
  28268. return listByTags;
  28269. };
  28270. /**
  28271. * Get a list of meshes by tags
  28272. * @param tagsQuery defines the tags query to use
  28273. * @param forEach defines a predicate used to filter results
  28274. * @returns an array of Mesh
  28275. */
  28276. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28277. return this._getByTags(this.meshes, tagsQuery, forEach);
  28278. };
  28279. /**
  28280. * Get a list of cameras by tags
  28281. * @param tagsQuery defines the tags query to use
  28282. * @param forEach defines a predicate used to filter results
  28283. * @returns an array of Camera
  28284. */
  28285. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28286. return this._getByTags(this.cameras, tagsQuery, forEach);
  28287. };
  28288. /**
  28289. * Get a list of lights by tags
  28290. * @param tagsQuery defines the tags query to use
  28291. * @param forEach defines a predicate used to filter results
  28292. * @returns an array of Light
  28293. */
  28294. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28295. return this._getByTags(this.lights, tagsQuery, forEach);
  28296. };
  28297. /**
  28298. * Get a list of materials by tags
  28299. * @param tagsQuery defines the tags query to use
  28300. * @param forEach defines a predicate used to filter results
  28301. * @returns an array of Material
  28302. */
  28303. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28304. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28305. };
  28306. /**
  28307. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28308. * This allowed control for front to back rendering or reversly depending of the special needs.
  28309. *
  28310. * @param renderingGroupId The rendering group id corresponding to its index
  28311. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28312. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28313. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28314. */
  28315. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28316. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28317. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28318. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28319. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28320. };
  28321. /**
  28322. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28323. *
  28324. * @param renderingGroupId The rendering group id corresponding to its index
  28325. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28326. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28327. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28328. */
  28329. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28330. if (depth === void 0) { depth = true; }
  28331. if (stencil === void 0) { stencil = true; }
  28332. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28333. };
  28334. /**
  28335. * Will flag all materials as dirty to trigger new shader compilation
  28336. * @param flag defines the flag used to specify which material part must be marked as dirty
  28337. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28338. */
  28339. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28340. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28341. var material = _a[_i];
  28342. if (predicate && !predicate(material)) {
  28343. continue;
  28344. }
  28345. material.markAsDirty(flag);
  28346. }
  28347. };
  28348. /** @ignore */
  28349. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28350. var _this = this;
  28351. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28352. this._activeRequests.push(request);
  28353. request.onCompleteObservable.add(function (request) {
  28354. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28355. });
  28356. return request;
  28357. };
  28358. /** @ignore */
  28359. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28360. var _this = this;
  28361. return new Promise(function (resolve, reject) {
  28362. _this._loadFile(url, function (data) {
  28363. resolve(data);
  28364. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28365. reject(exception);
  28366. });
  28367. });
  28368. };
  28369. // Statics
  28370. Scene._FOGMODE_NONE = 0;
  28371. Scene._FOGMODE_EXP = 1;
  28372. Scene._FOGMODE_EXP2 = 2;
  28373. Scene._FOGMODE_LINEAR = 3;
  28374. Scene._uniqueIdCounter = 0;
  28375. /**
  28376. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28377. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28378. */
  28379. Scene.MinDeltaTime = 1.0;
  28380. /**
  28381. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28382. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28383. */
  28384. Scene.MaxDeltaTime = 1000.0;
  28385. /** The distance in pixel that you have to move to prevent some events */
  28386. Scene.DragMovementThreshold = 10; // in pixels
  28387. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28388. Scene.LongPressDelay = 500; // in milliseconds
  28389. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28390. Scene.DoubleClickDelay = 300; // in milliseconds
  28391. /** If you need to check double click without raising a single click at first click, enable this flag */
  28392. Scene.ExclusiveDoubleClickMode = false;
  28393. return Scene;
  28394. }());
  28395. BABYLON.Scene = Scene;
  28396. })(BABYLON || (BABYLON = {}));
  28397. //# sourceMappingURL=babylon.scene.js.map
  28398. "use strict";
  28399. var BABYLON;
  28400. (function (BABYLON) {
  28401. /**
  28402. * Set of assets to keep when moving a scene into an asset container.
  28403. */
  28404. var KeepAssets = /** @class */ (function () {
  28405. function KeepAssets() {
  28406. /**
  28407. * Cameras to keep.
  28408. */
  28409. this.cameras = new Array();
  28410. /**
  28411. * Lights to keep.
  28412. */
  28413. this.lights = new Array();
  28414. /**
  28415. * Meshes to keep.
  28416. */
  28417. this.meshes = new Array();
  28418. /**
  28419. * Skeletons to keep.
  28420. */
  28421. this.skeletons = new Array();
  28422. /**
  28423. * ParticleSystems to keep.
  28424. */
  28425. this.particleSystems = new Array();
  28426. /**
  28427. * Animations to keep.
  28428. */
  28429. this.animations = new Array();
  28430. /**
  28431. * AnimationGroups to keep.
  28432. */
  28433. this.animationGroups = new Array();
  28434. /**
  28435. * MultiMaterials to keep.
  28436. */
  28437. this.multiMaterials = new Array();
  28438. /**
  28439. * Materials to keep.
  28440. */
  28441. this.materials = new Array();
  28442. /**
  28443. * MorphTargetManagers to keep.
  28444. */
  28445. this.morphTargetManagers = new Array();
  28446. /**
  28447. * Geometries to keep.
  28448. */
  28449. this.geometries = new Array();
  28450. /**
  28451. * TransformNodes to keep.
  28452. */
  28453. this.transformNodes = new Array();
  28454. /**
  28455. * LensFlareSystems to keep.
  28456. */
  28457. this.lensFlareSystems = new Array();
  28458. /**
  28459. * ShadowGenerators to keep.
  28460. */
  28461. this.shadowGenerators = new Array();
  28462. /**
  28463. * ActionManagers to keep.
  28464. */
  28465. this.actionManagers = new Array();
  28466. /**
  28467. * Sounds to keep.
  28468. */
  28469. this.sounds = new Array();
  28470. /**
  28471. * Textures to keep.
  28472. */
  28473. this.textures = new Array();
  28474. /**
  28475. * Effect layers to keep.
  28476. */
  28477. this.effectLayers = new Array();
  28478. }
  28479. return KeepAssets;
  28480. }());
  28481. BABYLON.KeepAssets = KeepAssets;
  28482. /**
  28483. * Container with a set of assets that can be added or removed from a scene.
  28484. */
  28485. var AssetContainer = /** @class */ (function () {
  28486. /**
  28487. * Instantiates an AssetContainer.
  28488. * @param scene The scene the AssetContainer belongs to.
  28489. */
  28490. function AssetContainer(scene) {
  28491. // Objects
  28492. /**
  28493. * Cameras populated in the container.
  28494. */
  28495. this.cameras = new Array();
  28496. /**
  28497. * Lights populated in the container.
  28498. */
  28499. this.lights = new Array();
  28500. /**
  28501. * Meshes populated in the container.
  28502. */
  28503. this.meshes = new Array();
  28504. /**
  28505. * Skeletons populated in the container.
  28506. */
  28507. this.skeletons = new Array();
  28508. /**
  28509. * ParticleSystems populated in the container.
  28510. */
  28511. this.particleSystems = new Array();
  28512. /**
  28513. * Animations populated in the container.
  28514. */
  28515. this.animations = new Array();
  28516. /**
  28517. * AnimationGroups populated in the container.
  28518. */
  28519. this.animationGroups = new Array();
  28520. /**
  28521. * MultiMaterials populated in the container.
  28522. */
  28523. this.multiMaterials = new Array();
  28524. /**
  28525. * Materials populated in the container.
  28526. */
  28527. this.materials = new Array();
  28528. /**
  28529. * MorphTargetManagers populated in the container.
  28530. */
  28531. this.morphTargetManagers = new Array();
  28532. /**
  28533. * Geometries populated in the container.
  28534. */
  28535. this.geometries = new Array();
  28536. /**
  28537. * TransformNodes populated in the container.
  28538. */
  28539. this.transformNodes = new Array();
  28540. /**
  28541. * LensFlareSystems populated in the container.
  28542. */
  28543. this.lensFlareSystems = new Array();
  28544. /**
  28545. * ShadowGenerators populated in the container.
  28546. */
  28547. this.shadowGenerators = new Array();
  28548. /**
  28549. * ActionManagers populated in the container.
  28550. */
  28551. this.actionManagers = new Array();
  28552. /**
  28553. * Sounds populated in the container.
  28554. */
  28555. this.sounds = new Array();
  28556. /**
  28557. * Textures populated in the container.
  28558. */
  28559. this.textures = new Array();
  28560. /**
  28561. * Effect layers populated in the container.
  28562. */
  28563. this.effectLayers = new Array();
  28564. this.scene = scene;
  28565. }
  28566. /**
  28567. * Adds all the assets from the container to the scene.
  28568. */
  28569. AssetContainer.prototype.addAllToScene = function () {
  28570. var _this = this;
  28571. this.cameras.forEach(function (o) {
  28572. _this.scene.addCamera(o);
  28573. });
  28574. this.lights.forEach(function (o) {
  28575. _this.scene.addLight(o);
  28576. });
  28577. this.meshes.forEach(function (o) {
  28578. _this.scene.addMesh(o);
  28579. });
  28580. this.skeletons.forEach(function (o) {
  28581. _this.scene.addSkeleton(o);
  28582. });
  28583. this.particleSystems.forEach(function (o) {
  28584. _this.scene.addParticleSystem(o);
  28585. });
  28586. this.animations.forEach(function (o) {
  28587. _this.scene.addAnimation(o);
  28588. });
  28589. this.animationGroups.forEach(function (o) {
  28590. _this.scene.addAnimationGroup(o);
  28591. });
  28592. this.multiMaterials.forEach(function (o) {
  28593. _this.scene.addMultiMaterial(o);
  28594. });
  28595. this.materials.forEach(function (o) {
  28596. _this.scene.addMaterial(o);
  28597. });
  28598. this.morphTargetManagers.forEach(function (o) {
  28599. _this.scene.addMorphTargetManager(o);
  28600. });
  28601. this.geometries.forEach(function (o) {
  28602. _this.scene.addGeometry(o);
  28603. });
  28604. this.transformNodes.forEach(function (o) {
  28605. _this.scene.addTransformNode(o);
  28606. });
  28607. this.lensFlareSystems.forEach(function (o) {
  28608. _this.scene.addLensFlareSystem(o);
  28609. });
  28610. this.actionManagers.forEach(function (o) {
  28611. _this.scene.addActionManager(o);
  28612. });
  28613. this.sounds.forEach(function (o) {
  28614. o.play();
  28615. o.autoplay = true;
  28616. _this.scene.mainSoundTrack.AddSound(o);
  28617. });
  28618. this.textures.forEach(function (o) {
  28619. _this.scene.addTexture(o);
  28620. });
  28621. this.effectLayers.forEach(function (o) {
  28622. _this.scene.addEffectLayer(o);
  28623. });
  28624. };
  28625. /**
  28626. * Removes all the assets in the container from the scene
  28627. */
  28628. AssetContainer.prototype.removeAllFromScene = function () {
  28629. var _this = this;
  28630. this.cameras.forEach(function (o) {
  28631. _this.scene.removeCamera(o);
  28632. });
  28633. this.lights.forEach(function (o) {
  28634. _this.scene.removeLight(o);
  28635. });
  28636. this.meshes.forEach(function (o) {
  28637. _this.scene.removeMesh(o);
  28638. });
  28639. this.skeletons.forEach(function (o) {
  28640. _this.scene.removeSkeleton(o);
  28641. });
  28642. this.particleSystems.forEach(function (o) {
  28643. _this.scene.removeParticleSystem(o);
  28644. });
  28645. this.animations.forEach(function (o) {
  28646. _this.scene.removeAnimation(o);
  28647. });
  28648. this.animationGroups.forEach(function (o) {
  28649. _this.scene.removeAnimationGroup(o);
  28650. });
  28651. this.multiMaterials.forEach(function (o) {
  28652. _this.scene.removeMultiMaterial(o);
  28653. });
  28654. this.materials.forEach(function (o) {
  28655. _this.scene.removeMaterial(o);
  28656. });
  28657. this.morphTargetManagers.forEach(function (o) {
  28658. _this.scene.removeMorphTargetManager(o);
  28659. });
  28660. this.geometries.forEach(function (o) {
  28661. _this.scene.removeGeometry(o);
  28662. });
  28663. this.transformNodes.forEach(function (o) {
  28664. _this.scene.removeTransformNode(o);
  28665. });
  28666. this.lensFlareSystems.forEach(function (o) {
  28667. _this.scene.removeLensFlareSystem(o);
  28668. });
  28669. this.actionManagers.forEach(function (o) {
  28670. _this.scene.removeActionManager(o);
  28671. });
  28672. this.sounds.forEach(function (o) {
  28673. o.stop();
  28674. o.autoplay = false;
  28675. _this.scene.mainSoundTrack.RemoveSound(o);
  28676. });
  28677. this.textures.forEach(function (o) {
  28678. _this.scene.removeTexture(o);
  28679. });
  28680. this.effectLayers.forEach(function (o) {
  28681. _this.scene.removeEffectLayer(o);
  28682. });
  28683. };
  28684. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28685. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28686. var asset = sourceAssets_1[_i];
  28687. var move = true;
  28688. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28689. var keepAsset = keepAssets_1[_a];
  28690. if (asset === keepAsset) {
  28691. move = false;
  28692. break;
  28693. }
  28694. }
  28695. if (move) {
  28696. targetAssets.push(asset);
  28697. }
  28698. }
  28699. };
  28700. /**
  28701. * Removes all the assets contained in the scene and adds them to the container.
  28702. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28703. */
  28704. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28705. if (keepAssets === undefined) {
  28706. keepAssets = new KeepAssets();
  28707. }
  28708. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28709. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28710. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28711. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28712. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28713. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28714. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28715. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28716. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28717. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28718. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28719. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28720. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28721. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28722. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28723. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28724. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28725. this.removeAllFromScene();
  28726. };
  28727. return AssetContainer;
  28728. }());
  28729. BABYLON.AssetContainer = AssetContainer;
  28730. })(BABYLON || (BABYLON = {}));
  28731. //# sourceMappingURL=babylon.assetContainer.js.map
  28732. "use strict";
  28733. var BABYLON;
  28734. (function (BABYLON) {
  28735. var Buffer = /** @class */ (function () {
  28736. /**
  28737. * Constructor
  28738. * @param engine the engine
  28739. * @param data the data to use for this buffer
  28740. * @param updatable whether the data is updatable
  28741. * @param stride the stride (optional)
  28742. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28743. * @param instanced whether the buffer is instanced (optional)
  28744. * @param useBytes set to true if the stride in in bytes (optional)
  28745. */
  28746. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28747. if (stride === void 0) { stride = 0; }
  28748. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28749. if (instanced === void 0) { instanced = false; }
  28750. if (useBytes === void 0) { useBytes = false; }
  28751. if (engine instanceof BABYLON.Mesh) {
  28752. this._engine = engine.getScene().getEngine();
  28753. }
  28754. else {
  28755. this._engine = engine;
  28756. }
  28757. this._updatable = updatable;
  28758. this._instanced = instanced;
  28759. this._data = data;
  28760. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28761. if (!postponeInternalCreation) {
  28762. this.create();
  28763. }
  28764. }
  28765. /**
  28766. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28767. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28768. * @param offset defines offset in the buffer (0 by default)
  28769. * @param size defines the size in floats of attributes (position is 3 for instance)
  28770. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28771. * @param instanced defines if the vertex buffer contains indexed data
  28772. * @param useBytes defines if the offset and stride are in bytes
  28773. * @returns the new vertex buffer
  28774. */
  28775. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28776. if (useBytes === void 0) { useBytes = false; }
  28777. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28778. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28779. // a lot of these parameters are ignored as they are overriden by the buffer
  28780. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28781. };
  28782. // Properties
  28783. Buffer.prototype.isUpdatable = function () {
  28784. return this._updatable;
  28785. };
  28786. Buffer.prototype.getData = function () {
  28787. return this._data;
  28788. };
  28789. Buffer.prototype.getBuffer = function () {
  28790. return this._buffer;
  28791. };
  28792. /**
  28793. * Gets the stride in float32 units (i.e. byte stride / 4).
  28794. * May not be an integer if the byte stride is not divisible by 4.
  28795. * DEPRECATED. Use byteStride instead.
  28796. * @returns the stride in float32 units
  28797. */
  28798. Buffer.prototype.getStrideSize = function () {
  28799. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28800. };
  28801. // Methods
  28802. Buffer.prototype.create = function (data) {
  28803. if (data === void 0) { data = null; }
  28804. if (!data && this._buffer) {
  28805. return; // nothing to do
  28806. }
  28807. data = data || this._data;
  28808. if (!data) {
  28809. return;
  28810. }
  28811. if (!this._buffer) {
  28812. if (this._updatable) {
  28813. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28814. this._data = data;
  28815. }
  28816. else {
  28817. this._buffer = this._engine.createVertexBuffer(data);
  28818. }
  28819. }
  28820. else if (this._updatable) {
  28821. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28822. this._data = data;
  28823. }
  28824. };
  28825. Buffer.prototype._rebuild = function () {
  28826. this._buffer = null;
  28827. this.create(this._data);
  28828. };
  28829. Buffer.prototype.update = function (data) {
  28830. this.create(data);
  28831. };
  28832. /**
  28833. * Updates the data directly.
  28834. * @param data the new data
  28835. * @param offset the new offset
  28836. * @param vertexCount the vertex count (optional)
  28837. * @param useBytes set to true if the offset is in bytes
  28838. */
  28839. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28840. if (useBytes === void 0) { useBytes = false; }
  28841. if (!this._buffer) {
  28842. return;
  28843. }
  28844. if (this._updatable) {
  28845. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28846. this._data = null;
  28847. }
  28848. };
  28849. Buffer.prototype.dispose = function () {
  28850. if (!this._buffer) {
  28851. return;
  28852. }
  28853. if (this._engine._releaseBuffer(this._buffer)) {
  28854. this._buffer = null;
  28855. }
  28856. };
  28857. return Buffer;
  28858. }());
  28859. BABYLON.Buffer = Buffer;
  28860. })(BABYLON || (BABYLON = {}));
  28861. //# sourceMappingURL=babylon.buffer.js.map
  28862. "use strict";
  28863. var BABYLON;
  28864. (function (BABYLON) {
  28865. var VertexBuffer = /** @class */ (function () {
  28866. /**
  28867. * Constructor
  28868. * @param engine the engine
  28869. * @param data the data to use for this vertex buffer
  28870. * @param kind the vertex buffer kind
  28871. * @param updatable whether the data is updatable
  28872. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28873. * @param stride the stride (optional)
  28874. * @param instanced whether the buffer is instanced (optional)
  28875. * @param offset the offset of the data (optional)
  28876. * @param size the number of components (optional)
  28877. * @param type the type of the component (optional)
  28878. * @param normalized whether the data contains normalized data (optional)
  28879. * @param useBytes set to true if stride and offset are in bytes (optional)
  28880. */
  28881. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28882. if (normalized === void 0) { normalized = false; }
  28883. if (useBytes === void 0) { useBytes = false; }
  28884. if (data instanceof BABYLON.Buffer) {
  28885. this._buffer = data;
  28886. this._ownsBuffer = false;
  28887. }
  28888. else {
  28889. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28890. this._ownsBuffer = true;
  28891. }
  28892. this._kind = kind;
  28893. if (type == undefined) {
  28894. var data_1 = this.getData();
  28895. this.type = VertexBuffer.FLOAT;
  28896. if (data_1 instanceof Int8Array)
  28897. this.type = VertexBuffer.BYTE;
  28898. else if (data_1 instanceof Uint8Array)
  28899. this.type = VertexBuffer.UNSIGNED_BYTE;
  28900. else if (data_1 instanceof Int16Array)
  28901. this.type = VertexBuffer.SHORT;
  28902. else if (data_1 instanceof Uint16Array)
  28903. this.type = VertexBuffer.UNSIGNED_SHORT;
  28904. else if (data_1 instanceof Int32Array)
  28905. this.type = VertexBuffer.INT;
  28906. else if (data_1 instanceof Uint32Array)
  28907. this.type = VertexBuffer.UNSIGNED_INT;
  28908. }
  28909. else {
  28910. this.type = type;
  28911. }
  28912. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28913. if (useBytes) {
  28914. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28915. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28916. this.byteOffset = offset || 0;
  28917. }
  28918. else {
  28919. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28920. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28921. this.byteOffset = (offset || 0) * typeByteLength;
  28922. }
  28923. this.normalized = normalized;
  28924. this._instanced = instanced !== undefined ? instanced : false;
  28925. this._instanceDivisor = instanced ? 1 : 0;
  28926. }
  28927. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28928. /**
  28929. * Gets or sets the instance divisor when in instanced mode
  28930. */
  28931. get: function () {
  28932. return this._instanceDivisor;
  28933. },
  28934. set: function (value) {
  28935. this._instanceDivisor = value;
  28936. if (value == 0) {
  28937. this._instanced = false;
  28938. }
  28939. else {
  28940. this._instanced = true;
  28941. }
  28942. },
  28943. enumerable: true,
  28944. configurable: true
  28945. });
  28946. VertexBuffer.prototype._rebuild = function () {
  28947. if (!this._buffer) {
  28948. return;
  28949. }
  28950. this._buffer._rebuild();
  28951. };
  28952. /**
  28953. * Returns the kind of the VertexBuffer (string).
  28954. */
  28955. VertexBuffer.prototype.getKind = function () {
  28956. return this._kind;
  28957. };
  28958. // Properties
  28959. /**
  28960. * Boolean : is the VertexBuffer updatable ?
  28961. */
  28962. VertexBuffer.prototype.isUpdatable = function () {
  28963. return this._buffer.isUpdatable();
  28964. };
  28965. /**
  28966. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28967. */
  28968. VertexBuffer.prototype.getData = function () {
  28969. return this._buffer.getData();
  28970. };
  28971. /**
  28972. * Returns the WebGLBuffer associated to the VertexBuffer.
  28973. */
  28974. VertexBuffer.prototype.getBuffer = function () {
  28975. return this._buffer.getBuffer();
  28976. };
  28977. /**
  28978. * Returns the stride as a multiple of the type byte length.
  28979. * DEPRECATED. Use byteStride instead.
  28980. */
  28981. VertexBuffer.prototype.getStrideSize = function () {
  28982. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28983. };
  28984. /**
  28985. * Returns the offset as a multiple of the type byte length.
  28986. * DEPRECATED. Use byteOffset instead.
  28987. */
  28988. VertexBuffer.prototype.getOffset = function () {
  28989. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28990. };
  28991. /**
  28992. * Returns the number of components per vertex attribute (integer).
  28993. */
  28994. VertexBuffer.prototype.getSize = function () {
  28995. return this._size;
  28996. };
  28997. /**
  28998. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28999. */
  29000. VertexBuffer.prototype.getIsInstanced = function () {
  29001. return this._instanced;
  29002. };
  29003. /**
  29004. * Returns the instancing divisor, zero for non-instanced (integer).
  29005. */
  29006. VertexBuffer.prototype.getInstanceDivisor = function () {
  29007. return this._instanceDivisor;
  29008. };
  29009. // Methods
  29010. /**
  29011. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29012. * Returns the created WebGLBuffer.
  29013. */
  29014. VertexBuffer.prototype.create = function (data) {
  29015. return this._buffer.create(data);
  29016. };
  29017. /**
  29018. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29019. * This function will create a new buffer if the current one is not updatable
  29020. * Returns the updated WebGLBuffer.
  29021. */
  29022. VertexBuffer.prototype.update = function (data) {
  29023. return this._buffer.update(data);
  29024. };
  29025. /**
  29026. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29027. * Returns the directly updated WebGLBuffer.
  29028. * @param data the new data
  29029. * @param offset the new offset
  29030. * @param useBytes set to true if the offset is in bytes
  29031. */
  29032. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29033. if (useBytes === void 0) { useBytes = false; }
  29034. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29035. };
  29036. /**
  29037. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29038. */
  29039. VertexBuffer.prototype.dispose = function () {
  29040. if (this._ownsBuffer) {
  29041. this._buffer.dispose();
  29042. }
  29043. };
  29044. /**
  29045. * Enumerates each value of this vertex buffer as numbers.
  29046. * @param count the number of values to enumerate
  29047. * @param callback the callback function called for each value
  29048. */
  29049. VertexBuffer.prototype.forEach = function (count, callback) {
  29050. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29051. };
  29052. Object.defineProperty(VertexBuffer, "PositionKind", {
  29053. get: function () {
  29054. return VertexBuffer._PositionKind;
  29055. },
  29056. enumerable: true,
  29057. configurable: true
  29058. });
  29059. Object.defineProperty(VertexBuffer, "NormalKind", {
  29060. get: function () {
  29061. return VertexBuffer._NormalKind;
  29062. },
  29063. enumerable: true,
  29064. configurable: true
  29065. });
  29066. Object.defineProperty(VertexBuffer, "TangentKind", {
  29067. get: function () {
  29068. return VertexBuffer._TangentKind;
  29069. },
  29070. enumerable: true,
  29071. configurable: true
  29072. });
  29073. Object.defineProperty(VertexBuffer, "UVKind", {
  29074. get: function () {
  29075. return VertexBuffer._UVKind;
  29076. },
  29077. enumerable: true,
  29078. configurable: true
  29079. });
  29080. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29081. get: function () {
  29082. return VertexBuffer._UV2Kind;
  29083. },
  29084. enumerable: true,
  29085. configurable: true
  29086. });
  29087. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29088. get: function () {
  29089. return VertexBuffer._UV3Kind;
  29090. },
  29091. enumerable: true,
  29092. configurable: true
  29093. });
  29094. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29095. get: function () {
  29096. return VertexBuffer._UV4Kind;
  29097. },
  29098. enumerable: true,
  29099. configurable: true
  29100. });
  29101. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29102. get: function () {
  29103. return VertexBuffer._UV5Kind;
  29104. },
  29105. enumerable: true,
  29106. configurable: true
  29107. });
  29108. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29109. get: function () {
  29110. return VertexBuffer._UV6Kind;
  29111. },
  29112. enumerable: true,
  29113. configurable: true
  29114. });
  29115. Object.defineProperty(VertexBuffer, "ColorKind", {
  29116. get: function () {
  29117. return VertexBuffer._ColorKind;
  29118. },
  29119. enumerable: true,
  29120. configurable: true
  29121. });
  29122. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29123. get: function () {
  29124. return VertexBuffer._MatricesIndicesKind;
  29125. },
  29126. enumerable: true,
  29127. configurable: true
  29128. });
  29129. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29130. get: function () {
  29131. return VertexBuffer._MatricesWeightsKind;
  29132. },
  29133. enumerable: true,
  29134. configurable: true
  29135. });
  29136. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29137. get: function () {
  29138. return VertexBuffer._MatricesIndicesExtraKind;
  29139. },
  29140. enumerable: true,
  29141. configurable: true
  29142. });
  29143. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29144. get: function () {
  29145. return VertexBuffer._MatricesWeightsExtraKind;
  29146. },
  29147. enumerable: true,
  29148. configurable: true
  29149. });
  29150. /**
  29151. * Deduces the stride given a kind.
  29152. * @param kind The kind string to deduce
  29153. * @returns The deduced stride
  29154. */
  29155. VertexBuffer.DeduceStride = function (kind) {
  29156. switch (kind) {
  29157. case VertexBuffer.UVKind:
  29158. case VertexBuffer.UV2Kind:
  29159. case VertexBuffer.UV3Kind:
  29160. case VertexBuffer.UV4Kind:
  29161. case VertexBuffer.UV5Kind:
  29162. case VertexBuffer.UV6Kind:
  29163. return 2;
  29164. case VertexBuffer.NormalKind:
  29165. case VertexBuffer.PositionKind:
  29166. return 3;
  29167. case VertexBuffer.ColorKind:
  29168. case VertexBuffer.MatricesIndicesKind:
  29169. case VertexBuffer.MatricesIndicesExtraKind:
  29170. case VertexBuffer.MatricesWeightsKind:
  29171. case VertexBuffer.MatricesWeightsExtraKind:
  29172. case VertexBuffer.TangentKind:
  29173. return 4;
  29174. default:
  29175. throw new Error("Invalid kind '" + kind + "'");
  29176. }
  29177. };
  29178. /**
  29179. * Gets the byte length of the given type.
  29180. * @param type the type
  29181. * @returns the number of bytes
  29182. */
  29183. VertexBuffer.GetTypeByteLength = function (type) {
  29184. switch (type) {
  29185. case VertexBuffer.BYTE:
  29186. case VertexBuffer.UNSIGNED_BYTE:
  29187. return 1;
  29188. case VertexBuffer.SHORT:
  29189. case VertexBuffer.UNSIGNED_SHORT:
  29190. return 2;
  29191. case VertexBuffer.INT:
  29192. case VertexBuffer.FLOAT:
  29193. return 4;
  29194. default:
  29195. throw new Error("Invalid type '" + type + "'");
  29196. }
  29197. };
  29198. /**
  29199. * Enumerates each value of the given parameters as numbers.
  29200. * @param data the data to enumerate
  29201. * @param byteOffset the byte offset of the data
  29202. * @param byteStride the byte stride of the data
  29203. * @param componentCount the number of components per element
  29204. * @param componentType the type of the component
  29205. * @param count the total number of components
  29206. * @param normalized whether the data is normalized
  29207. * @param callback the callback function called for each value
  29208. */
  29209. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29210. if (data instanceof Array) {
  29211. var offset = byteOffset / 4;
  29212. var stride = byteStride / 4;
  29213. for (var index = 0; index < count; index += componentCount) {
  29214. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29215. callback(data[offset + componentIndex], index + componentIndex);
  29216. }
  29217. offset += stride;
  29218. }
  29219. }
  29220. else {
  29221. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29222. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29223. for (var index = 0; index < count; index += componentCount) {
  29224. var componentByteOffset = byteOffset;
  29225. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29226. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29227. callback(value, index + componentIndex);
  29228. componentByteOffset += componentByteLength;
  29229. }
  29230. byteOffset += byteStride;
  29231. }
  29232. }
  29233. };
  29234. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29235. switch (type) {
  29236. case VertexBuffer.BYTE: {
  29237. var value = dataView.getInt8(byteOffset);
  29238. if (normalized) {
  29239. value = (value + 0.5) / 127.5;
  29240. }
  29241. return value;
  29242. }
  29243. case VertexBuffer.UNSIGNED_BYTE: {
  29244. var value = dataView.getUint8(byteOffset);
  29245. if (normalized) {
  29246. value = value / 255;
  29247. }
  29248. return value;
  29249. }
  29250. case VertexBuffer.SHORT: {
  29251. var value = dataView.getInt16(byteOffset, true);
  29252. if (normalized) {
  29253. value = (value + 0.5) / 16383.5;
  29254. }
  29255. return value;
  29256. }
  29257. case VertexBuffer.UNSIGNED_SHORT: {
  29258. var value = dataView.getUint16(byteOffset, true);
  29259. if (normalized) {
  29260. value = value / 65535;
  29261. }
  29262. return value;
  29263. }
  29264. case VertexBuffer.FLOAT: {
  29265. return dataView.getFloat32(byteOffset, true);
  29266. }
  29267. default: {
  29268. throw new Error("Invalid component type " + type);
  29269. }
  29270. }
  29271. };
  29272. /**
  29273. * The byte type.
  29274. */
  29275. VertexBuffer.BYTE = 5120;
  29276. /**
  29277. * The unsigned byte type.
  29278. */
  29279. VertexBuffer.UNSIGNED_BYTE = 5121;
  29280. /**
  29281. * The short type.
  29282. */
  29283. VertexBuffer.SHORT = 5122;
  29284. /**
  29285. * The unsigned short type.
  29286. */
  29287. VertexBuffer.UNSIGNED_SHORT = 5123;
  29288. /**
  29289. * The integer type.
  29290. */
  29291. VertexBuffer.INT = 5124;
  29292. /**
  29293. * The unsigned integer type.
  29294. */
  29295. VertexBuffer.UNSIGNED_INT = 5125;
  29296. /**
  29297. * The float type.
  29298. */
  29299. VertexBuffer.FLOAT = 5126;
  29300. // Enums
  29301. VertexBuffer._PositionKind = "position";
  29302. VertexBuffer._NormalKind = "normal";
  29303. VertexBuffer._TangentKind = "tangent";
  29304. VertexBuffer._UVKind = "uv";
  29305. VertexBuffer._UV2Kind = "uv2";
  29306. VertexBuffer._UV3Kind = "uv3";
  29307. VertexBuffer._UV4Kind = "uv4";
  29308. VertexBuffer._UV5Kind = "uv5";
  29309. VertexBuffer._UV6Kind = "uv6";
  29310. VertexBuffer._ColorKind = "color";
  29311. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29312. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29313. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29314. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29315. return VertexBuffer;
  29316. }());
  29317. BABYLON.VertexBuffer = VertexBuffer;
  29318. })(BABYLON || (BABYLON = {}));
  29319. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29320. "use strict";
  29321. var BABYLON;
  29322. (function (BABYLON) {
  29323. /**
  29324. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29325. */
  29326. var DummyInternalTextureTracker = /** @class */ (function () {
  29327. function DummyInternalTextureTracker() {
  29328. /**
  29329. * Gets or set the previous tracker in the list
  29330. */
  29331. this.previous = null;
  29332. /**
  29333. * Gets or set the next tracker in the list
  29334. */
  29335. this.next = null;
  29336. }
  29337. return DummyInternalTextureTracker;
  29338. }());
  29339. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29340. })(BABYLON || (BABYLON = {}));
  29341. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29342. "use strict";
  29343. var BABYLON;
  29344. (function (BABYLON) {
  29345. /**
  29346. * Class used to store data associated with WebGL texture data for the engine
  29347. * This class should not be used directly
  29348. */
  29349. var InternalTexture = /** @class */ (function () {
  29350. /**
  29351. * Creates a new InternalTexture
  29352. * @param engine defines the engine to use
  29353. * @param dataSource defines the type of data that will be used
  29354. */
  29355. function InternalTexture(engine, dataSource) {
  29356. /**
  29357. * Observable called when the texture is loaded
  29358. */
  29359. this.onLoadedObservable = new BABYLON.Observable();
  29360. /**
  29361. * Gets or set the previous tracker in the list
  29362. */
  29363. this.previous = null;
  29364. /**
  29365. * Gets or set the next tracker in the list
  29366. */
  29367. this.next = null;
  29368. // Private
  29369. /** @ignore */
  29370. this._initialSlot = -1;
  29371. /** @ignore */
  29372. this._designatedSlot = -1;
  29373. /** @ignore */
  29374. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29375. /** @ignore */
  29376. this._comparisonFunction = 0;
  29377. /** @ignore */
  29378. this._references = 1;
  29379. this._engine = engine;
  29380. this._dataSource = dataSource;
  29381. this._webGLTexture = engine._createTexture();
  29382. }
  29383. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29384. /**
  29385. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29386. */
  29387. get: function () {
  29388. return this._dataSource;
  29389. },
  29390. enumerable: true,
  29391. configurable: true
  29392. });
  29393. /**
  29394. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29395. */
  29396. InternalTexture.prototype.incrementReferences = function () {
  29397. this._references++;
  29398. };
  29399. /**
  29400. * Change the size of the texture (not the size of the content)
  29401. * @param width defines the new width
  29402. * @param height defines the new height
  29403. * @param depth defines the new depth (1 by default)
  29404. */
  29405. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29406. if (depth === void 0) { depth = 1; }
  29407. this.width = width;
  29408. this.height = height;
  29409. this.depth = depth;
  29410. this.baseWidth = width;
  29411. this.baseHeight = height;
  29412. this.baseDepth = depth;
  29413. this._size = width * height * depth;
  29414. };
  29415. /** @ignore */
  29416. InternalTexture.prototype._rebuild = function () {
  29417. var _this = this;
  29418. var proxy;
  29419. this.isReady = false;
  29420. this._cachedCoordinatesMode = null;
  29421. this._cachedWrapU = null;
  29422. this._cachedWrapV = null;
  29423. this._cachedAnisotropicFilteringLevel = null;
  29424. switch (this._dataSource) {
  29425. case InternalTexture.DATASOURCE_TEMP:
  29426. return;
  29427. case InternalTexture.DATASOURCE_URL:
  29428. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29429. _this.isReady = true;
  29430. }, null, this._buffer, undefined, this.format);
  29431. proxy._swapAndDie(this);
  29432. return;
  29433. case InternalTexture.DATASOURCE_RAW:
  29434. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29435. proxy._swapAndDie(this);
  29436. this.isReady = true;
  29437. return;
  29438. case InternalTexture.DATASOURCE_RAW3D:
  29439. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29440. proxy._swapAndDie(this);
  29441. this.isReady = true;
  29442. return;
  29443. case InternalTexture.DATASOURCE_DYNAMIC:
  29444. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29445. proxy._swapAndDie(this);
  29446. // The engine will make sure to update content so no need to flag it as isReady = true
  29447. return;
  29448. case InternalTexture.DATASOURCE_RENDERTARGET:
  29449. var options = new BABYLON.RenderTargetCreationOptions();
  29450. options.generateDepthBuffer = this._generateDepthBuffer;
  29451. options.generateMipMaps = this.generateMipMaps;
  29452. options.generateStencilBuffer = this._generateStencilBuffer;
  29453. options.samplingMode = this.samplingMode;
  29454. options.type = this.type;
  29455. if (this.isCube) {
  29456. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29457. }
  29458. else {
  29459. var size = {
  29460. width: this.width,
  29461. height: this.height
  29462. };
  29463. proxy = this._engine.createRenderTargetTexture(size, options);
  29464. }
  29465. proxy._swapAndDie(this);
  29466. this.isReady = true;
  29467. return;
  29468. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29469. var depthTextureOptions = {
  29470. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29471. comparisonFunction: this._comparisonFunction,
  29472. generateStencil: this._generateStencilBuffer,
  29473. isCube: this.isCube
  29474. };
  29475. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29476. proxy._swapAndDie(this);
  29477. this.isReady = true;
  29478. return;
  29479. case InternalTexture.DATASOURCE_CUBE:
  29480. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29481. _this.isReady = true;
  29482. }, null, this.format, this._extension);
  29483. proxy._swapAndDie(this);
  29484. return;
  29485. case InternalTexture.DATASOURCE_CUBERAW:
  29486. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29487. proxy._swapAndDie(this);
  29488. this.isReady = true;
  29489. return;
  29490. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29491. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29492. if (proxy) {
  29493. proxy._swapAndDie(_this);
  29494. }
  29495. _this.isReady = true;
  29496. }, null, this.format, this._extension);
  29497. return;
  29498. }
  29499. };
  29500. InternalTexture.prototype._swapAndDie = function (target) {
  29501. target._webGLTexture = this._webGLTexture;
  29502. if (this._framebuffer) {
  29503. target._framebuffer = this._framebuffer;
  29504. }
  29505. if (this._depthStencilBuffer) {
  29506. target._depthStencilBuffer = this._depthStencilBuffer;
  29507. }
  29508. if (this._lodTextureHigh) {
  29509. if (target._lodTextureHigh) {
  29510. target._lodTextureHigh.dispose();
  29511. }
  29512. target._lodTextureHigh = this._lodTextureHigh;
  29513. }
  29514. if (this._lodTextureMid) {
  29515. if (target._lodTextureMid) {
  29516. target._lodTextureMid.dispose();
  29517. }
  29518. target._lodTextureMid = this._lodTextureMid;
  29519. }
  29520. if (this._lodTextureLow) {
  29521. if (target._lodTextureLow) {
  29522. target._lodTextureLow.dispose();
  29523. }
  29524. target._lodTextureLow = this._lodTextureLow;
  29525. }
  29526. var cache = this._engine.getLoadedTexturesCache();
  29527. var index = cache.indexOf(this);
  29528. if (index !== -1) {
  29529. cache.splice(index, 1);
  29530. }
  29531. };
  29532. /**
  29533. * Dispose the current allocated resources
  29534. */
  29535. InternalTexture.prototype.dispose = function () {
  29536. if (!this._webGLTexture) {
  29537. return;
  29538. }
  29539. this._references--;
  29540. if (this._references === 0) {
  29541. this._engine._releaseTexture(this);
  29542. this._webGLTexture = null;
  29543. this.previous = null;
  29544. this.next = null;
  29545. }
  29546. };
  29547. /**
  29548. * The source of the texture data is unknown
  29549. */
  29550. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29551. /**
  29552. * Texture data comes from an URL
  29553. */
  29554. InternalTexture.DATASOURCE_URL = 1;
  29555. /**
  29556. * Texture data is only used for temporary storage
  29557. */
  29558. InternalTexture.DATASOURCE_TEMP = 2;
  29559. /**
  29560. * Texture data comes from raw data (ArrayBuffer)
  29561. */
  29562. InternalTexture.DATASOURCE_RAW = 3;
  29563. /**
  29564. * Texture content is dynamic (video or dynamic texture)
  29565. */
  29566. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29567. /**
  29568. * Texture content is generated by rendering to it
  29569. */
  29570. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29571. /**
  29572. * Texture content is part of a multi render target process
  29573. */
  29574. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29575. /**
  29576. * Texture data comes from a cube data file
  29577. */
  29578. InternalTexture.DATASOURCE_CUBE = 7;
  29579. /**
  29580. * Texture data comes from a raw cube data
  29581. */
  29582. InternalTexture.DATASOURCE_CUBERAW = 8;
  29583. /**
  29584. * Texture data come from a prefiltered cube data file
  29585. */
  29586. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29587. /**
  29588. * Texture content is raw 3D data
  29589. */
  29590. InternalTexture.DATASOURCE_RAW3D = 10;
  29591. /**
  29592. * Texture content is a depth texture
  29593. */
  29594. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29595. return InternalTexture;
  29596. }());
  29597. BABYLON.InternalTexture = InternalTexture;
  29598. })(BABYLON || (BABYLON = {}));
  29599. //# sourceMappingURL=babylon.internalTexture.js.map
  29600. "use strict";
  29601. var BABYLON;
  29602. (function (BABYLON) {
  29603. var BaseTexture = /** @class */ (function () {
  29604. function BaseTexture(scene) {
  29605. this._hasAlpha = false;
  29606. this.getAlphaFromRGB = false;
  29607. this.level = 1;
  29608. this.coordinatesIndex = 0;
  29609. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29610. /**
  29611. * | Value | Type | Description |
  29612. * | ----- | ------------------ | ----------- |
  29613. * | 0 | CLAMP_ADDRESSMODE | |
  29614. * | 1 | WRAP_ADDRESSMODE | |
  29615. * | 2 | MIRROR_ADDRESSMODE | |
  29616. */
  29617. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29618. /**
  29619. * | Value | Type | Description |
  29620. * | ----- | ------------------ | ----------- |
  29621. * | 0 | CLAMP_ADDRESSMODE | |
  29622. * | 1 | WRAP_ADDRESSMODE | |
  29623. * | 2 | MIRROR_ADDRESSMODE | |
  29624. */
  29625. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29626. /**
  29627. * | Value | Type | Description |
  29628. * | ----- | ------------------ | ----------- |
  29629. * | 0 | CLAMP_ADDRESSMODE | |
  29630. * | 1 | WRAP_ADDRESSMODE | |
  29631. * | 2 | MIRROR_ADDRESSMODE | |
  29632. */
  29633. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29634. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29635. this.isCube = false;
  29636. this.is3D = false;
  29637. this.gammaSpace = true;
  29638. this.invertZ = false;
  29639. this.lodLevelInAlpha = false;
  29640. this.lodGenerationOffset = 0.0;
  29641. this.lodGenerationScale = 0.8;
  29642. this.isRenderTarget = false;
  29643. this.animations = new Array();
  29644. /**
  29645. * An event triggered when the texture is disposed.
  29646. */
  29647. this.onDisposeObservable = new BABYLON.Observable();
  29648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29649. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29650. if (this._scene) {
  29651. this._scene.textures.push(this);
  29652. }
  29653. this._uid = null;
  29654. }
  29655. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29656. get: function () {
  29657. return this._hasAlpha;
  29658. },
  29659. set: function (value) {
  29660. if (this._hasAlpha === value) {
  29661. return;
  29662. }
  29663. this._hasAlpha = value;
  29664. if (this._scene) {
  29665. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29666. }
  29667. },
  29668. enumerable: true,
  29669. configurable: true
  29670. });
  29671. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29672. get: function () {
  29673. return this._coordinatesMode;
  29674. },
  29675. /**
  29676. * How a texture is mapped.
  29677. *
  29678. * | Value | Type | Description |
  29679. * | ----- | ----------------------------------- | ----------- |
  29680. * | 0 | EXPLICIT_MODE | |
  29681. * | 1 | SPHERICAL_MODE | |
  29682. * | 2 | PLANAR_MODE | |
  29683. * | 3 | CUBIC_MODE | |
  29684. * | 4 | PROJECTION_MODE | |
  29685. * | 5 | SKYBOX_MODE | |
  29686. * | 6 | INVCUBIC_MODE | |
  29687. * | 7 | EQUIRECTANGULAR_MODE | |
  29688. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29689. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29690. */
  29691. set: function (value) {
  29692. if (this._coordinatesMode === value) {
  29693. return;
  29694. }
  29695. this._coordinatesMode = value;
  29696. if (this._scene) {
  29697. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29698. }
  29699. },
  29700. enumerable: true,
  29701. configurable: true
  29702. });
  29703. Object.defineProperty(BaseTexture.prototype, "uid", {
  29704. get: function () {
  29705. if (!this._uid) {
  29706. this._uid = BABYLON.Tools.RandomId();
  29707. }
  29708. return this._uid;
  29709. },
  29710. enumerable: true,
  29711. configurable: true
  29712. });
  29713. BaseTexture.prototype.toString = function () {
  29714. return this.name;
  29715. };
  29716. BaseTexture.prototype.getClassName = function () {
  29717. return "BaseTexture";
  29718. };
  29719. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29720. set: function (callback) {
  29721. if (this._onDisposeObserver) {
  29722. this.onDisposeObservable.remove(this._onDisposeObserver);
  29723. }
  29724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29725. },
  29726. enumerable: true,
  29727. configurable: true
  29728. });
  29729. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29730. get: function () {
  29731. return true;
  29732. },
  29733. enumerable: true,
  29734. configurable: true
  29735. });
  29736. BaseTexture.prototype.getScene = function () {
  29737. return this._scene;
  29738. };
  29739. BaseTexture.prototype.getTextureMatrix = function () {
  29740. return BABYLON.Matrix.IdentityReadOnly;
  29741. };
  29742. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29743. return BABYLON.Matrix.IdentityReadOnly;
  29744. };
  29745. BaseTexture.prototype.getInternalTexture = function () {
  29746. return this._texture;
  29747. };
  29748. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29749. return !this.isBlocking || this.isReady();
  29750. };
  29751. BaseTexture.prototype.isReady = function () {
  29752. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29753. this.delayLoad();
  29754. return false;
  29755. }
  29756. if (this._texture) {
  29757. return this._texture.isReady;
  29758. }
  29759. return false;
  29760. };
  29761. BaseTexture.prototype.getSize = function () {
  29762. if (this._texture && this._texture.width) {
  29763. return new BABYLON.Size(this._texture.width, this._texture.height);
  29764. }
  29765. if (this._texture && this._texture._size) {
  29766. return new BABYLON.Size(this._texture._size, this._texture._size);
  29767. }
  29768. return BABYLON.Size.Zero();
  29769. };
  29770. BaseTexture.prototype.getBaseSize = function () {
  29771. if (!this.isReady() || !this._texture)
  29772. return BABYLON.Size.Zero();
  29773. if (this._texture._size) {
  29774. return new BABYLON.Size(this._texture._size, this._texture._size);
  29775. }
  29776. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29777. };
  29778. BaseTexture.prototype.scale = function (ratio) {
  29779. };
  29780. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29781. get: function () {
  29782. return false;
  29783. },
  29784. enumerable: true,
  29785. configurable: true
  29786. });
  29787. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29788. if (!this._scene) {
  29789. return null;
  29790. }
  29791. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29792. for (var index = 0; index < texturesCache.length; index++) {
  29793. var texturesCacheEntry = texturesCache[index];
  29794. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29795. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29796. texturesCacheEntry.incrementReferences();
  29797. return texturesCacheEntry;
  29798. }
  29799. }
  29800. }
  29801. return null;
  29802. };
  29803. BaseTexture.prototype._rebuild = function () {
  29804. };
  29805. BaseTexture.prototype.delayLoad = function () {
  29806. };
  29807. BaseTexture.prototype.clone = function () {
  29808. return null;
  29809. };
  29810. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29811. get: function () {
  29812. if (!this._texture) {
  29813. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29814. }
  29815. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29816. },
  29817. enumerable: true,
  29818. configurable: true
  29819. });
  29820. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29821. get: function () {
  29822. if (!this._texture) {
  29823. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29824. }
  29825. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29826. },
  29827. enumerable: true,
  29828. configurable: true
  29829. });
  29830. BaseTexture.prototype.readPixels = function (faceIndex) {
  29831. if (faceIndex === void 0) { faceIndex = 0; }
  29832. if (!this._texture) {
  29833. return null;
  29834. }
  29835. var size = this.getSize();
  29836. var scene = this.getScene();
  29837. if (!scene) {
  29838. return null;
  29839. }
  29840. var engine = scene.getEngine();
  29841. if (this._texture.isCube) {
  29842. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29843. }
  29844. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29845. };
  29846. BaseTexture.prototype.releaseInternalTexture = function () {
  29847. if (this._texture) {
  29848. this._texture.dispose();
  29849. this._texture = null;
  29850. }
  29851. };
  29852. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29853. get: function () {
  29854. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29855. return null;
  29856. }
  29857. if (!this._texture._sphericalPolynomial) {
  29858. this._texture._sphericalPolynomial =
  29859. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29860. }
  29861. return this._texture._sphericalPolynomial;
  29862. },
  29863. set: function (value) {
  29864. if (this._texture) {
  29865. this._texture._sphericalPolynomial = value;
  29866. }
  29867. },
  29868. enumerable: true,
  29869. configurable: true
  29870. });
  29871. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29872. get: function () {
  29873. if (this._texture) {
  29874. return this._texture._lodTextureHigh;
  29875. }
  29876. return null;
  29877. },
  29878. enumerable: true,
  29879. configurable: true
  29880. });
  29881. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29882. get: function () {
  29883. if (this._texture) {
  29884. return this._texture._lodTextureMid;
  29885. }
  29886. return null;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29892. get: function () {
  29893. if (this._texture) {
  29894. return this._texture._lodTextureLow;
  29895. }
  29896. return null;
  29897. },
  29898. enumerable: true,
  29899. configurable: true
  29900. });
  29901. BaseTexture.prototype.dispose = function () {
  29902. if (!this._scene) {
  29903. return;
  29904. }
  29905. // Animations
  29906. this._scene.stopAnimation(this);
  29907. // Remove from scene
  29908. this._scene._removePendingData(this);
  29909. var index = this._scene.textures.indexOf(this);
  29910. if (index >= 0) {
  29911. this._scene.textures.splice(index, 1);
  29912. }
  29913. if (this._texture === undefined) {
  29914. return;
  29915. }
  29916. // Release
  29917. this.releaseInternalTexture();
  29918. // Callback
  29919. this.onDisposeObservable.notifyObservers(this);
  29920. this.onDisposeObservable.clear();
  29921. };
  29922. BaseTexture.prototype.serialize = function () {
  29923. if (!this.name) {
  29924. return null;
  29925. }
  29926. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29927. // Animations
  29928. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29929. return serializationObject;
  29930. };
  29931. BaseTexture.WhenAllReady = function (textures, callback) {
  29932. var numRemaining = textures.length;
  29933. if (numRemaining === 0) {
  29934. callback();
  29935. return;
  29936. }
  29937. var _loop_1 = function () {
  29938. texture = textures[i];
  29939. if (texture.isReady()) {
  29940. if (--numRemaining === 0) {
  29941. callback();
  29942. }
  29943. }
  29944. else {
  29945. onLoadObservable = texture.onLoadObservable;
  29946. var onLoadCallback_1 = function () {
  29947. onLoadObservable.removeCallback(onLoadCallback_1);
  29948. if (--numRemaining === 0) {
  29949. callback();
  29950. }
  29951. };
  29952. onLoadObservable.add(onLoadCallback_1);
  29953. }
  29954. };
  29955. var texture, onLoadObservable;
  29956. for (var i = 0; i < textures.length; i++) {
  29957. _loop_1();
  29958. }
  29959. };
  29960. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29961. __decorate([
  29962. BABYLON.serialize()
  29963. ], BaseTexture.prototype, "name", void 0);
  29964. __decorate([
  29965. BABYLON.serialize("hasAlpha")
  29966. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29967. __decorate([
  29968. BABYLON.serialize()
  29969. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29970. __decorate([
  29971. BABYLON.serialize()
  29972. ], BaseTexture.prototype, "level", void 0);
  29973. __decorate([
  29974. BABYLON.serialize()
  29975. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29976. __decorate([
  29977. BABYLON.serialize("coordinatesMode")
  29978. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29979. __decorate([
  29980. BABYLON.serialize()
  29981. ], BaseTexture.prototype, "wrapU", void 0);
  29982. __decorate([
  29983. BABYLON.serialize()
  29984. ], BaseTexture.prototype, "wrapV", void 0);
  29985. __decorate([
  29986. BABYLON.serialize()
  29987. ], BaseTexture.prototype, "wrapR", void 0);
  29988. __decorate([
  29989. BABYLON.serialize()
  29990. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29991. __decorate([
  29992. BABYLON.serialize()
  29993. ], BaseTexture.prototype, "isCube", void 0);
  29994. __decorate([
  29995. BABYLON.serialize()
  29996. ], BaseTexture.prototype, "is3D", void 0);
  29997. __decorate([
  29998. BABYLON.serialize()
  29999. ], BaseTexture.prototype, "gammaSpace", void 0);
  30000. __decorate([
  30001. BABYLON.serialize()
  30002. ], BaseTexture.prototype, "invertZ", void 0);
  30003. __decorate([
  30004. BABYLON.serialize()
  30005. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30006. __decorate([
  30007. BABYLON.serialize()
  30008. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30009. __decorate([
  30010. BABYLON.serialize()
  30011. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30012. __decorate([
  30013. BABYLON.serialize()
  30014. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30015. return BaseTexture;
  30016. }());
  30017. BABYLON.BaseTexture = BaseTexture;
  30018. })(BABYLON || (BABYLON = {}));
  30019. //# sourceMappingURL=babylon.baseTexture.js.map
  30020. "use strict";
  30021. var BABYLON;
  30022. (function (BABYLON) {
  30023. var Texture = /** @class */ (function (_super) {
  30024. __extends(Texture, _super);
  30025. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30026. if (noMipmap === void 0) { noMipmap = false; }
  30027. if (invertY === void 0) { invertY = true; }
  30028. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30029. if (onLoad === void 0) { onLoad = null; }
  30030. if (onError === void 0) { onError = null; }
  30031. if (buffer === void 0) { buffer = null; }
  30032. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30033. var _this = _super.call(this, scene) || this;
  30034. _this.uOffset = 0;
  30035. _this.vOffset = 0;
  30036. _this.uScale = 1.0;
  30037. _this.vScale = 1.0;
  30038. _this.uAng = 0;
  30039. _this.vAng = 0;
  30040. _this.wAng = 0;
  30041. _this._isBlocking = true;
  30042. _this.name = url || "";
  30043. _this.url = url;
  30044. _this._noMipmap = noMipmap;
  30045. _this._invertY = invertY;
  30046. _this._samplingMode = samplingMode;
  30047. _this._buffer = buffer;
  30048. _this._deleteBuffer = deleteBuffer;
  30049. if (format) {
  30050. _this._format = format;
  30051. }
  30052. scene = _this.getScene();
  30053. if (!scene) {
  30054. return _this;
  30055. }
  30056. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30057. var load = function () {
  30058. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30059. _this.onLoadObservable.notifyObservers(_this);
  30060. }
  30061. if (onLoad) {
  30062. onLoad();
  30063. }
  30064. if (!_this.isBlocking && scene) {
  30065. scene.resetCachedMaterial();
  30066. }
  30067. };
  30068. if (!_this.url) {
  30069. _this._delayedOnLoad = load;
  30070. _this._delayedOnError = onError;
  30071. return _this;
  30072. }
  30073. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30074. if (!_this._texture) {
  30075. if (!scene.useDelayedTextureLoading) {
  30076. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30077. if (deleteBuffer) {
  30078. delete _this._buffer;
  30079. }
  30080. }
  30081. else {
  30082. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30083. _this._delayedOnLoad = load;
  30084. _this._delayedOnError = onError;
  30085. }
  30086. }
  30087. else {
  30088. if (_this._texture.isReady) {
  30089. BABYLON.Tools.SetImmediate(function () { return load(); });
  30090. }
  30091. else {
  30092. _this._texture.onLoadedObservable.add(load);
  30093. }
  30094. }
  30095. return _this;
  30096. }
  30097. Object.defineProperty(Texture.prototype, "noMipmap", {
  30098. get: function () {
  30099. return this._noMipmap;
  30100. },
  30101. enumerable: true,
  30102. configurable: true
  30103. });
  30104. Object.defineProperty(Texture.prototype, "isBlocking", {
  30105. get: function () {
  30106. return this._isBlocking;
  30107. },
  30108. set: function (value) {
  30109. this._isBlocking = value;
  30110. },
  30111. enumerable: true,
  30112. configurable: true
  30113. });
  30114. Object.defineProperty(Texture.prototype, "samplingMode", {
  30115. get: function () {
  30116. return this._samplingMode;
  30117. },
  30118. enumerable: true,
  30119. configurable: true
  30120. });
  30121. Texture.prototype.updateURL = function (url) {
  30122. this.url = url;
  30123. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30124. this.delayLoad();
  30125. };
  30126. Texture.prototype.delayLoad = function () {
  30127. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30128. return;
  30129. }
  30130. var scene = this.getScene();
  30131. if (!scene) {
  30132. return;
  30133. }
  30134. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30135. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30136. if (!this._texture) {
  30137. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30138. if (this._deleteBuffer) {
  30139. delete this._buffer;
  30140. }
  30141. }
  30142. else {
  30143. if (this._delayedOnLoad) {
  30144. if (this._texture.isReady) {
  30145. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30146. }
  30147. else {
  30148. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30149. }
  30150. }
  30151. }
  30152. this._delayedOnLoad = null;
  30153. this._delayedOnError = null;
  30154. };
  30155. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30156. if (!this._texture) {
  30157. return;
  30158. }
  30159. var scene = this.getScene();
  30160. if (!scene) {
  30161. return;
  30162. }
  30163. this._samplingMode = samplingMode;
  30164. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30165. };
  30166. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30167. x *= this.uScale;
  30168. y *= this.vScale;
  30169. x -= 0.5 * this.uScale;
  30170. y -= 0.5 * this.vScale;
  30171. z -= 0.5;
  30172. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30173. t.x += 0.5 * this.uScale + this.uOffset;
  30174. t.y += 0.5 * this.vScale + this.vOffset;
  30175. t.z += 0.5;
  30176. };
  30177. Texture.prototype.getTextureMatrix = function () {
  30178. var _this = this;
  30179. if (this.uOffset === this._cachedUOffset &&
  30180. this.vOffset === this._cachedVOffset &&
  30181. this.uScale === this._cachedUScale &&
  30182. this.vScale === this._cachedVScale &&
  30183. this.uAng === this._cachedUAng &&
  30184. this.vAng === this._cachedVAng &&
  30185. this.wAng === this._cachedWAng) {
  30186. return this._cachedTextureMatrix;
  30187. }
  30188. this._cachedUOffset = this.uOffset;
  30189. this._cachedVOffset = this.vOffset;
  30190. this._cachedUScale = this.uScale;
  30191. this._cachedVScale = this.vScale;
  30192. this._cachedUAng = this.uAng;
  30193. this._cachedVAng = this.vAng;
  30194. this._cachedWAng = this.wAng;
  30195. if (!this._cachedTextureMatrix) {
  30196. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30197. this._rowGenerationMatrix = new BABYLON.Matrix();
  30198. this._t0 = BABYLON.Vector3.Zero();
  30199. this._t1 = BABYLON.Vector3.Zero();
  30200. this._t2 = BABYLON.Vector3.Zero();
  30201. }
  30202. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30203. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30204. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30205. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30206. this._t1.subtractInPlace(this._t0);
  30207. this._t2.subtractInPlace(this._t0);
  30208. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30209. this._cachedTextureMatrix.m[0] = this._t1.x;
  30210. this._cachedTextureMatrix.m[1] = this._t1.y;
  30211. this._cachedTextureMatrix.m[2] = this._t1.z;
  30212. this._cachedTextureMatrix.m[4] = this._t2.x;
  30213. this._cachedTextureMatrix.m[5] = this._t2.y;
  30214. this._cachedTextureMatrix.m[6] = this._t2.z;
  30215. this._cachedTextureMatrix.m[8] = this._t0.x;
  30216. this._cachedTextureMatrix.m[9] = this._t0.y;
  30217. this._cachedTextureMatrix.m[10] = this._t0.z;
  30218. var scene = this.getScene();
  30219. if (!scene) {
  30220. return this._cachedTextureMatrix;
  30221. }
  30222. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30223. return mat.hasTexture(_this);
  30224. });
  30225. return this._cachedTextureMatrix;
  30226. };
  30227. Texture.prototype.getReflectionTextureMatrix = function () {
  30228. var _this = this;
  30229. var scene = this.getScene();
  30230. if (!scene) {
  30231. return this._cachedTextureMatrix;
  30232. }
  30233. if (this.uOffset === this._cachedUOffset &&
  30234. this.vOffset === this._cachedVOffset &&
  30235. this.uScale === this._cachedUScale &&
  30236. this.vScale === this._cachedVScale &&
  30237. this.coordinatesMode === this._cachedCoordinatesMode) {
  30238. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30239. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30240. return this._cachedTextureMatrix;
  30241. }
  30242. }
  30243. else {
  30244. return this._cachedTextureMatrix;
  30245. }
  30246. }
  30247. if (!this._cachedTextureMatrix) {
  30248. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30249. }
  30250. if (!this._projectionModeMatrix) {
  30251. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30252. }
  30253. this._cachedUOffset = this.uOffset;
  30254. this._cachedVOffset = this.vOffset;
  30255. this._cachedUScale = this.uScale;
  30256. this._cachedVScale = this.vScale;
  30257. this._cachedCoordinatesMode = this.coordinatesMode;
  30258. switch (this.coordinatesMode) {
  30259. case Texture.PLANAR_MODE:
  30260. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30261. this._cachedTextureMatrix[0] = this.uScale;
  30262. this._cachedTextureMatrix[5] = this.vScale;
  30263. this._cachedTextureMatrix[12] = this.uOffset;
  30264. this._cachedTextureMatrix[13] = this.vOffset;
  30265. break;
  30266. case Texture.PROJECTION_MODE:
  30267. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30268. this._projectionModeMatrix.m[0] = 0.5;
  30269. this._projectionModeMatrix.m[5] = -0.5;
  30270. this._projectionModeMatrix.m[10] = 0.0;
  30271. this._projectionModeMatrix.m[12] = 0.5;
  30272. this._projectionModeMatrix.m[13] = 0.5;
  30273. this._projectionModeMatrix.m[14] = 1.0;
  30274. this._projectionModeMatrix.m[15] = 1.0;
  30275. var projectionMatrix = scene.getProjectionMatrix();
  30276. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30277. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30278. break;
  30279. default:
  30280. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30281. break;
  30282. }
  30283. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30284. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30285. });
  30286. return this._cachedTextureMatrix;
  30287. };
  30288. Texture.prototype.clone = function () {
  30289. var _this = this;
  30290. return BABYLON.SerializationHelper.Clone(function () {
  30291. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30292. }, this);
  30293. };
  30294. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30295. get: function () {
  30296. if (!this._onLoadObservable) {
  30297. this._onLoadObservable = new BABYLON.Observable();
  30298. }
  30299. return this._onLoadObservable;
  30300. },
  30301. enumerable: true,
  30302. configurable: true
  30303. });
  30304. Texture.prototype.serialize = function () {
  30305. var serializationObject = _super.prototype.serialize.call(this);
  30306. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30307. serializationObject.base64String = this._buffer;
  30308. serializationObject.name = serializationObject.name.replace("data:", "");
  30309. }
  30310. serializationObject.invertY = this._invertY;
  30311. serializationObject.samplingMode = this.samplingMode;
  30312. return serializationObject;
  30313. };
  30314. Texture.prototype.getClassName = function () {
  30315. return "Texture";
  30316. };
  30317. Texture.prototype.dispose = function () {
  30318. _super.prototype.dispose.call(this);
  30319. if (this.onLoadObservable) {
  30320. this.onLoadObservable.clear();
  30321. this._onLoadObservable = null;
  30322. }
  30323. this._delayedOnLoad = null;
  30324. this._delayedOnError = null;
  30325. };
  30326. // Statics
  30327. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30328. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30329. if (onLoad === void 0) { onLoad = null; }
  30330. if (onError === void 0) { onError = null; }
  30331. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30332. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30333. };
  30334. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30335. if (parsedTexture.customType) {
  30336. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30337. // Update Sampling Mode
  30338. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30339. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30340. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30341. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30342. }
  30343. }
  30344. return parsedCustomTexture;
  30345. }
  30346. if (parsedTexture.isCube) {
  30347. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30348. }
  30349. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30350. return null;
  30351. }
  30352. var texture = BABYLON.SerializationHelper.Parse(function () {
  30353. var generateMipMaps = true;
  30354. if (parsedTexture.noMipmap) {
  30355. generateMipMaps = false;
  30356. }
  30357. if (parsedTexture.mirrorPlane) {
  30358. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30359. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30360. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30361. return mirrorTexture;
  30362. }
  30363. else if (parsedTexture.isRenderTarget) {
  30364. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30365. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30366. return renderTargetTexture;
  30367. }
  30368. else {
  30369. var texture;
  30370. if (parsedTexture.base64String) {
  30371. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30372. }
  30373. else {
  30374. var url = rootUrl + parsedTexture.name;
  30375. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30376. url = parsedTexture.url;
  30377. }
  30378. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30379. }
  30380. return texture;
  30381. }
  30382. }, parsedTexture, scene);
  30383. // Update Sampling Mode
  30384. if (parsedTexture.samplingMode) {
  30385. var sampling = parsedTexture.samplingMode;
  30386. if (texture._samplingMode !== sampling) {
  30387. texture.updateSamplingMode(sampling);
  30388. }
  30389. }
  30390. // Animations
  30391. if (parsedTexture.animations) {
  30392. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30393. var parsedAnimation = parsedTexture.animations[animationIndex];
  30394. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30395. }
  30396. }
  30397. return texture;
  30398. };
  30399. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30400. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30401. if (noMipmap === void 0) { noMipmap = false; }
  30402. if (invertY === void 0) { invertY = true; }
  30403. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30404. if (onLoad === void 0) { onLoad = null; }
  30405. if (onError === void 0) { onError = null; }
  30406. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30407. if (name.substr(0, 5) !== "data:") {
  30408. name = "data:" + name;
  30409. }
  30410. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30411. };
  30412. // Constants
  30413. Texture.NEAREST_SAMPLINGMODE = 1;
  30414. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30415. Texture.BILINEAR_SAMPLINGMODE = 2;
  30416. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30417. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30418. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30419. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30420. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30421. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30422. Texture.NEAREST_LINEAR = 7;
  30423. Texture.NEAREST_NEAREST = 8;
  30424. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30425. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30426. Texture.LINEAR_LINEAR = 11;
  30427. Texture.LINEAR_NEAREST = 12;
  30428. Texture.EXPLICIT_MODE = 0;
  30429. Texture.SPHERICAL_MODE = 1;
  30430. Texture.PLANAR_MODE = 2;
  30431. Texture.CUBIC_MODE = 3;
  30432. Texture.PROJECTION_MODE = 4;
  30433. Texture.SKYBOX_MODE = 5;
  30434. Texture.INVCUBIC_MODE = 6;
  30435. Texture.EQUIRECTANGULAR_MODE = 7;
  30436. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30437. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30438. Texture.CLAMP_ADDRESSMODE = 0;
  30439. Texture.WRAP_ADDRESSMODE = 1;
  30440. Texture.MIRROR_ADDRESSMODE = 2;
  30441. /**
  30442. * 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
  30443. */
  30444. Texture.UseSerializedUrlIfAny = false;
  30445. __decorate([
  30446. BABYLON.serialize()
  30447. ], Texture.prototype, "url", void 0);
  30448. __decorate([
  30449. BABYLON.serialize()
  30450. ], Texture.prototype, "uOffset", void 0);
  30451. __decorate([
  30452. BABYLON.serialize()
  30453. ], Texture.prototype, "vOffset", void 0);
  30454. __decorate([
  30455. BABYLON.serialize()
  30456. ], Texture.prototype, "uScale", void 0);
  30457. __decorate([
  30458. BABYLON.serialize()
  30459. ], Texture.prototype, "vScale", void 0);
  30460. __decorate([
  30461. BABYLON.serialize()
  30462. ], Texture.prototype, "uAng", void 0);
  30463. __decorate([
  30464. BABYLON.serialize()
  30465. ], Texture.prototype, "vAng", void 0);
  30466. __decorate([
  30467. BABYLON.serialize()
  30468. ], Texture.prototype, "wAng", void 0);
  30469. __decorate([
  30470. BABYLON.serialize()
  30471. ], Texture.prototype, "isBlocking", null);
  30472. return Texture;
  30473. }(BABYLON.BaseTexture));
  30474. BABYLON.Texture = Texture;
  30475. })(BABYLON || (BABYLON = {}));
  30476. //# sourceMappingURL=babylon.texture.js.map
  30477. "use strict";
  30478. var BABYLON;
  30479. (function (BABYLON) {
  30480. var _InstancesBatch = /** @class */ (function () {
  30481. function _InstancesBatch() {
  30482. this.mustReturn = false;
  30483. this.visibleInstances = new Array();
  30484. this.renderSelf = new Array();
  30485. }
  30486. return _InstancesBatch;
  30487. }());
  30488. BABYLON._InstancesBatch = _InstancesBatch;
  30489. var Mesh = /** @class */ (function (_super) {
  30490. __extends(Mesh, _super);
  30491. /**
  30492. * @constructor
  30493. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30494. * @param {Scene} scene The scene to add this mesh to.
  30495. * @param {Node} parent The parent of this mesh, if it has one
  30496. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30497. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30498. * When false, achieved by calling a clone(), also passing False.
  30499. * This will make creation of children, recursive.
  30500. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30501. */
  30502. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30503. if (scene === void 0) { scene = null; }
  30504. if (parent === void 0) { parent = null; }
  30505. if (source === void 0) { source = null; }
  30506. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30507. var _this = _super.call(this, name, scene) || this;
  30508. // Events
  30509. /**
  30510. * An event triggered before rendering the mesh
  30511. */
  30512. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30513. /**
  30514. * An event triggered after rendering the mesh
  30515. */
  30516. _this.onAfterRenderObservable = new BABYLON.Observable();
  30517. /**
  30518. * An event triggered before drawing the mesh
  30519. */
  30520. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30521. // Members
  30522. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30523. _this.instances = new Array();
  30524. _this._LODLevels = new Array();
  30525. _this._visibleInstances = {};
  30526. _this._renderIdForInstances = new Array();
  30527. _this._batchCache = new _InstancesBatch();
  30528. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30529. // Use by builder only to know what orientation were the mesh build in.
  30530. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30531. _this.overrideMaterialSideOrientation = null;
  30532. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30533. // Will be used to save a source mesh reference, If any
  30534. _this._source = null;
  30535. scene = _this.getScene();
  30536. if (source) {
  30537. // Source mesh
  30538. _this._source = source;
  30539. // Geometry
  30540. if (source._geometry) {
  30541. source._geometry.applyToMesh(_this);
  30542. }
  30543. // Deep copy
  30544. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30545. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30546. // Metadata
  30547. if (source.metadata && source.metadata.clone) {
  30548. _this.metadata = source.metadata.clone();
  30549. }
  30550. else {
  30551. _this.metadata = source.metadata;
  30552. }
  30553. // Tags
  30554. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30555. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30556. }
  30557. // Parent
  30558. _this.parent = source.parent;
  30559. // Pivot
  30560. _this.setPivotMatrix(source.getPivotMatrix());
  30561. _this.id = name + "." + source.id;
  30562. // Material
  30563. _this.material = source.material;
  30564. var index;
  30565. if (!doNotCloneChildren) {
  30566. // Children
  30567. var directDescendants = source.getDescendants(true);
  30568. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30569. var child = directDescendants[index_1];
  30570. if (child.clone) {
  30571. child.clone(name + "." + child.name, _this);
  30572. }
  30573. }
  30574. }
  30575. // Physics clone
  30576. var physicsEngine = _this.getScene().getPhysicsEngine();
  30577. if (clonePhysicsImpostor && physicsEngine) {
  30578. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30579. if (impostor) {
  30580. _this.physicsImpostor = impostor.clone(_this);
  30581. }
  30582. }
  30583. // Particles
  30584. for (index = 0; index < scene.particleSystems.length; index++) {
  30585. var system = scene.particleSystems[index];
  30586. if (system.emitter === source) {
  30587. system.clone(system.name, _this);
  30588. }
  30589. }
  30590. _this.computeWorldMatrix(true);
  30591. }
  30592. // Parent
  30593. if (parent !== null) {
  30594. _this.parent = parent;
  30595. }
  30596. return _this;
  30597. }
  30598. Object.defineProperty(Mesh, "FRONTSIDE", {
  30599. /**
  30600. * Mesh side orientation : usually the external or front surface
  30601. */
  30602. get: function () {
  30603. return Mesh._FRONTSIDE;
  30604. },
  30605. enumerable: true,
  30606. configurable: true
  30607. });
  30608. Object.defineProperty(Mesh, "BACKSIDE", {
  30609. /**
  30610. * Mesh side orientation : usually the internal or back surface
  30611. */
  30612. get: function () {
  30613. return Mesh._BACKSIDE;
  30614. },
  30615. enumerable: true,
  30616. configurable: true
  30617. });
  30618. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30619. /**
  30620. * Mesh side orientation : both internal and external or front and back surfaces
  30621. */
  30622. get: function () {
  30623. return Mesh._DOUBLESIDE;
  30624. },
  30625. enumerable: true,
  30626. configurable: true
  30627. });
  30628. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30629. /**
  30630. * Mesh side orientation : by default, `FRONTSIDE`
  30631. */
  30632. get: function () {
  30633. return Mesh._DEFAULTSIDE;
  30634. },
  30635. enumerable: true,
  30636. configurable: true
  30637. });
  30638. Object.defineProperty(Mesh, "NO_CAP", {
  30639. /**
  30640. * Mesh cap setting : no cap
  30641. */
  30642. get: function () {
  30643. return Mesh._NO_CAP;
  30644. },
  30645. enumerable: true,
  30646. configurable: true
  30647. });
  30648. Object.defineProperty(Mesh, "CAP_START", {
  30649. /**
  30650. * Mesh cap setting : one cap at the beginning of the mesh
  30651. */
  30652. get: function () {
  30653. return Mesh._CAP_START;
  30654. },
  30655. enumerable: true,
  30656. configurable: true
  30657. });
  30658. Object.defineProperty(Mesh, "CAP_END", {
  30659. /**
  30660. * Mesh cap setting : one cap at the end of the mesh
  30661. */
  30662. get: function () {
  30663. return Mesh._CAP_END;
  30664. },
  30665. enumerable: true,
  30666. configurable: true
  30667. });
  30668. Object.defineProperty(Mesh, "CAP_ALL", {
  30669. /**
  30670. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30671. */
  30672. get: function () {
  30673. return Mesh._CAP_ALL;
  30674. },
  30675. enumerable: true,
  30676. configurable: true
  30677. });
  30678. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30679. set: function (callback) {
  30680. if (this._onBeforeDrawObserver) {
  30681. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30682. }
  30683. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30684. },
  30685. enumerable: true,
  30686. configurable: true
  30687. });
  30688. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30689. get: function () {
  30690. return this._morphTargetManager;
  30691. },
  30692. set: function (value) {
  30693. if (this._morphTargetManager === value) {
  30694. return;
  30695. }
  30696. this._morphTargetManager = value;
  30697. this._syncGeometryWithMorphTargetManager();
  30698. },
  30699. enumerable: true,
  30700. configurable: true
  30701. });
  30702. Object.defineProperty(Mesh.prototype, "source", {
  30703. get: function () {
  30704. return this._source;
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30710. get: function () {
  30711. return this._unIndexed;
  30712. },
  30713. set: function (value) {
  30714. if (this._unIndexed !== value) {
  30715. this._unIndexed = value;
  30716. this._markSubMeshesAsAttributesDirty();
  30717. }
  30718. },
  30719. enumerable: true,
  30720. configurable: true
  30721. });
  30722. // Methods
  30723. /**
  30724. * Returns the string "Mesh".
  30725. */
  30726. Mesh.prototype.getClassName = function () {
  30727. return "Mesh";
  30728. };
  30729. /**
  30730. * Returns a string.
  30731. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30732. */
  30733. Mesh.prototype.toString = function (fullDetails) {
  30734. var ret = _super.prototype.toString.call(this, fullDetails);
  30735. ret += ", n vertices: " + this.getTotalVertices();
  30736. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30737. if (this.animations) {
  30738. for (var i = 0; i < this.animations.length; i++) {
  30739. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30740. }
  30741. }
  30742. if (fullDetails) {
  30743. if (this._geometry) {
  30744. var ib = this.getIndices();
  30745. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30746. if (vb && ib) {
  30747. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30748. }
  30749. }
  30750. else {
  30751. ret += ", flat shading: UNKNOWN";
  30752. }
  30753. }
  30754. return ret;
  30755. };
  30756. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30757. /**
  30758. * True if the mesh has some Levels Of Details (LOD).
  30759. * Returns a boolean.
  30760. */
  30761. get: function () {
  30762. return this._LODLevels.length > 0;
  30763. },
  30764. enumerable: true,
  30765. configurable: true
  30766. });
  30767. /**
  30768. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30769. * @returns an array of {BABYLON.MeshLODLevel}
  30770. */
  30771. Mesh.prototype.getLODLevels = function () {
  30772. return this._LODLevels;
  30773. };
  30774. Mesh.prototype._sortLODLevels = function () {
  30775. this._LODLevels.sort(function (a, b) {
  30776. if (a.distance < b.distance) {
  30777. return 1;
  30778. }
  30779. if (a.distance > b.distance) {
  30780. return -1;
  30781. }
  30782. return 0;
  30783. });
  30784. };
  30785. /**
  30786. * Add a mesh as LOD level triggered at the given distance.
  30787. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30788. * @param {number} distance The distance from the center of the object to show this level
  30789. * @param {Mesh} mesh The mesh to be added as LOD level
  30790. * @return {Mesh} This mesh (for chaining)
  30791. */
  30792. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30793. if (mesh && mesh._masterMesh) {
  30794. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30795. return this;
  30796. }
  30797. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30798. this._LODLevels.push(level);
  30799. if (mesh) {
  30800. mesh._masterMesh = this;
  30801. }
  30802. this._sortLODLevels();
  30803. return this;
  30804. };
  30805. /**
  30806. * Returns the LOD level mesh at the passed distance or null if not found.
  30807. * It is related to the method `addLODLevel(distance, mesh)`.
  30808. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30809. * Returns an object Mesh or `null`.
  30810. */
  30811. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30812. for (var index = 0; index < this._LODLevels.length; index++) {
  30813. var level = this._LODLevels[index];
  30814. if (level.distance === distance) {
  30815. return level.mesh;
  30816. }
  30817. }
  30818. return null;
  30819. };
  30820. /**
  30821. * Remove a mesh from the LOD array
  30822. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30823. * @param {Mesh} mesh The mesh to be removed.
  30824. * @return {Mesh} This mesh (for chaining)
  30825. */
  30826. Mesh.prototype.removeLODLevel = function (mesh) {
  30827. for (var index = 0; index < this._LODLevels.length; index++) {
  30828. if (this._LODLevels[index].mesh === mesh) {
  30829. this._LODLevels.splice(index, 1);
  30830. if (mesh) {
  30831. mesh._masterMesh = null;
  30832. }
  30833. }
  30834. }
  30835. this._sortLODLevels();
  30836. return this;
  30837. };
  30838. /**
  30839. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30840. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30841. */
  30842. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30843. if (!this._LODLevels || this._LODLevels.length === 0) {
  30844. return this;
  30845. }
  30846. var bSphere;
  30847. if (boundingSphere) {
  30848. bSphere = boundingSphere;
  30849. }
  30850. else {
  30851. var boundingInfo = this.getBoundingInfo();
  30852. bSphere = boundingInfo.boundingSphere;
  30853. }
  30854. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30855. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30856. if (this.onLODLevelSelection) {
  30857. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30858. }
  30859. return this;
  30860. }
  30861. for (var index = 0; index < this._LODLevels.length; index++) {
  30862. var level = this._LODLevels[index];
  30863. if (level.distance < distanceToCamera) {
  30864. if (level.mesh) {
  30865. level.mesh._preActivate();
  30866. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30867. }
  30868. if (this.onLODLevelSelection) {
  30869. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30870. }
  30871. return level.mesh;
  30872. }
  30873. }
  30874. if (this.onLODLevelSelection) {
  30875. this.onLODLevelSelection(distanceToCamera, this, this);
  30876. }
  30877. return this;
  30878. };
  30879. Object.defineProperty(Mesh.prototype, "geometry", {
  30880. /**
  30881. * Returns the mesh internal Geometry object.
  30882. */
  30883. get: function () {
  30884. return this._geometry;
  30885. },
  30886. enumerable: true,
  30887. configurable: true
  30888. });
  30889. /**
  30890. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30891. */
  30892. Mesh.prototype.getTotalVertices = function () {
  30893. if (this._geometry === null || this._geometry === undefined) {
  30894. return 0;
  30895. }
  30896. return this._geometry.getTotalVertices();
  30897. };
  30898. /**
  30899. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30900. * 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.
  30901. * You can force the copy with forceCopy === true
  30902. * Returns null if the mesh has no geometry or no vertex buffer.
  30903. * Possible `kind` values :
  30904. * - BABYLON.VertexBuffer.PositionKind
  30905. * - BABYLON.VertexBuffer.UVKind
  30906. * - BABYLON.VertexBuffer.UV2Kind
  30907. * - BABYLON.VertexBuffer.UV3Kind
  30908. * - BABYLON.VertexBuffer.UV4Kind
  30909. * - BABYLON.VertexBuffer.UV5Kind
  30910. * - BABYLON.VertexBuffer.UV6Kind
  30911. * - BABYLON.VertexBuffer.ColorKind
  30912. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30913. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30914. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30915. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30916. */
  30917. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30918. if (!this._geometry) {
  30919. return null;
  30920. }
  30921. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30922. };
  30923. /**
  30924. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30925. * Returns `null` if the mesh has no geometry.
  30926. * Possible `kind` values :
  30927. * - BABYLON.VertexBuffer.PositionKind
  30928. * - BABYLON.VertexBuffer.UVKind
  30929. * - BABYLON.VertexBuffer.UV2Kind
  30930. * - BABYLON.VertexBuffer.UV3Kind
  30931. * - BABYLON.VertexBuffer.UV4Kind
  30932. * - BABYLON.VertexBuffer.UV5Kind
  30933. * - BABYLON.VertexBuffer.UV6Kind
  30934. * - BABYLON.VertexBuffer.ColorKind
  30935. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30936. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30937. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30938. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30939. */
  30940. Mesh.prototype.getVertexBuffer = function (kind) {
  30941. if (!this._geometry) {
  30942. return null;
  30943. }
  30944. return this._geometry.getVertexBuffer(kind);
  30945. };
  30946. /**
  30947. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30948. * Possible `kind` values :
  30949. * - BABYLON.VertexBuffer.PositionKind
  30950. * - BABYLON.VertexBuffer.UVKind
  30951. * - BABYLON.VertexBuffer.UV2Kind
  30952. * - BABYLON.VertexBuffer.UV3Kind
  30953. * - BABYLON.VertexBuffer.UV4Kind
  30954. * - BABYLON.VertexBuffer.UV5Kind
  30955. * - BABYLON.VertexBuffer.UV6Kind
  30956. * - BABYLON.VertexBuffer.ColorKind
  30957. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30958. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30959. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30960. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30961. */
  30962. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30963. if (!this._geometry) {
  30964. if (this._delayInfo) {
  30965. return this._delayInfo.indexOf(kind) !== -1;
  30966. }
  30967. return false;
  30968. }
  30969. return this._geometry.isVerticesDataPresent(kind);
  30970. };
  30971. /**
  30972. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30973. * Possible `kind` values :
  30974. * - BABYLON.VertexBuffer.PositionKind
  30975. * - BABYLON.VertexBuffer.UVKind
  30976. * - BABYLON.VertexBuffer.UV2Kind
  30977. * - BABYLON.VertexBuffer.UV3Kind
  30978. * - BABYLON.VertexBuffer.UV4Kind
  30979. * - BABYLON.VertexBuffer.UV5Kind
  30980. * - BABYLON.VertexBuffer.UV6Kind
  30981. * - BABYLON.VertexBuffer.ColorKind
  30982. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30983. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30984. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30985. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30986. */
  30987. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30988. if (!this._geometry) {
  30989. if (this._delayInfo) {
  30990. return this._delayInfo.indexOf(kind) !== -1;
  30991. }
  30992. return false;
  30993. }
  30994. return this._geometry.isVertexBufferUpdatable(kind);
  30995. };
  30996. /**
  30997. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30998. * Possible `kind` values :
  30999. * - BABYLON.VertexBuffer.PositionKind
  31000. * - BABYLON.VertexBuffer.UVKind
  31001. * - BABYLON.VertexBuffer.UV2Kind
  31002. * - BABYLON.VertexBuffer.UV3Kind
  31003. * - BABYLON.VertexBuffer.UV4Kind
  31004. * - BABYLON.VertexBuffer.UV5Kind
  31005. * - BABYLON.VertexBuffer.UV6Kind
  31006. * - BABYLON.VertexBuffer.ColorKind
  31007. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31008. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31009. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31010. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31011. */
  31012. Mesh.prototype.getVerticesDataKinds = function () {
  31013. if (!this._geometry) {
  31014. var result = new Array();
  31015. if (this._delayInfo) {
  31016. this._delayInfo.forEach(function (kind, index, array) {
  31017. result.push(kind);
  31018. });
  31019. }
  31020. return result;
  31021. }
  31022. return this._geometry.getVerticesDataKinds();
  31023. };
  31024. /**
  31025. * Returns a positive integer : the total number of indices in this mesh geometry.
  31026. * Returns zero if the mesh has no geometry.
  31027. */
  31028. Mesh.prototype.getTotalIndices = function () {
  31029. if (!this._geometry) {
  31030. return 0;
  31031. }
  31032. return this._geometry.getTotalIndices();
  31033. };
  31034. /**
  31035. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31036. * 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.
  31037. * Returns an empty array if the mesh has no geometry.
  31038. */
  31039. Mesh.prototype.getIndices = function (copyWhenShared) {
  31040. if (!this._geometry) {
  31041. return [];
  31042. }
  31043. return this._geometry.getIndices(copyWhenShared);
  31044. };
  31045. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31046. get: function () {
  31047. return this._masterMesh !== null && this._masterMesh !== undefined;
  31048. },
  31049. enumerable: true,
  31050. configurable: true
  31051. });
  31052. /**
  31053. * Determine if the current mesh is ready to be rendered
  31054. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31055. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31056. * @returns true if all associated assets are ready (material, textures, shaders)
  31057. */
  31058. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31059. if (completeCheck === void 0) { completeCheck = false; }
  31060. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31061. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31062. return false;
  31063. }
  31064. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31065. return false;
  31066. }
  31067. if (!this.subMeshes || this.subMeshes.length === 0) {
  31068. return true;
  31069. }
  31070. if (!completeCheck) {
  31071. return true;
  31072. }
  31073. var engine = this.getEngine();
  31074. var scene = this.getScene();
  31075. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31076. this.computeWorldMatrix();
  31077. var mat = this.material || scene.defaultMaterial;
  31078. if (mat) {
  31079. if (mat.storeEffectOnSubMeshes) {
  31080. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31081. var subMesh = _a[_i];
  31082. var effectiveMaterial = subMesh.getMaterial();
  31083. if (effectiveMaterial) {
  31084. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31085. return false;
  31086. }
  31087. }
  31088. }
  31089. }
  31090. else {
  31091. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31092. return false;
  31093. }
  31094. }
  31095. }
  31096. // Shadows
  31097. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31098. var light = _c[_b];
  31099. var generator = light.getShadowGenerator();
  31100. if (generator) {
  31101. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31102. var subMesh = _e[_d];
  31103. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31104. return false;
  31105. }
  31106. }
  31107. }
  31108. }
  31109. // LOD
  31110. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31111. var lod = _g[_f];
  31112. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31113. return false;
  31114. }
  31115. }
  31116. return true;
  31117. };
  31118. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31119. /**
  31120. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31121. * This property is pertinent only for updatable parametric shapes.
  31122. */
  31123. get: function () {
  31124. return this._areNormalsFrozen;
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. /**
  31130. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31131. * It has no effect at all on other shapes.
  31132. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31133. * Returns the Mesh.
  31134. */
  31135. Mesh.prototype.freezeNormals = function () {
  31136. this._areNormalsFrozen = true;
  31137. return this;
  31138. };
  31139. /**
  31140. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31141. * It has no effect at all on other shapes.
  31142. * It reactivates the mesh normals computation if it was previously frozen.
  31143. * Returns the Mesh.
  31144. */
  31145. Mesh.prototype.unfreezeNormals = function () {
  31146. this._areNormalsFrozen = false;
  31147. return this;
  31148. };
  31149. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31150. /**
  31151. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31152. */
  31153. set: function (count) {
  31154. this._overridenInstanceCount = count;
  31155. },
  31156. enumerable: true,
  31157. configurable: true
  31158. });
  31159. // Methods
  31160. Mesh.prototype._preActivate = function () {
  31161. var sceneRenderId = this.getScene().getRenderId();
  31162. if (this._preActivateId === sceneRenderId) {
  31163. return this;
  31164. }
  31165. this._preActivateId = sceneRenderId;
  31166. this._visibleInstances = null;
  31167. return this;
  31168. };
  31169. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31170. if (this._visibleInstances) {
  31171. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31172. }
  31173. return this;
  31174. };
  31175. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31176. if (!this._visibleInstances) {
  31177. this._visibleInstances = {};
  31178. this._visibleInstances.defaultRenderId = renderId;
  31179. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31180. }
  31181. if (!this._visibleInstances[renderId]) {
  31182. this._visibleInstances[renderId] = new Array();
  31183. }
  31184. this._visibleInstances[renderId].push(instance);
  31185. return this;
  31186. };
  31187. /**
  31188. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31189. * This means the mesh underlying bounding box and sphere are recomputed.
  31190. * Returns the Mesh.
  31191. */
  31192. Mesh.prototype.refreshBoundingInfo = function () {
  31193. return this._refreshBoundingInfo(false);
  31194. };
  31195. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31196. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31197. return this;
  31198. }
  31199. var data = this._getPositionData(applySkeleton);
  31200. if (data) {
  31201. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31202. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31203. }
  31204. if (this.subMeshes) {
  31205. for (var index = 0; index < this.subMeshes.length; index++) {
  31206. this.subMeshes[index].refreshBoundingInfo();
  31207. }
  31208. }
  31209. this._updateBoundingInfo();
  31210. return this;
  31211. };
  31212. Mesh.prototype._getPositionData = function (applySkeleton) {
  31213. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31214. if (data && applySkeleton && this.skeleton) {
  31215. data = BABYLON.Tools.Slice(data);
  31216. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31217. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31218. if (matricesWeightsData && matricesIndicesData) {
  31219. var needExtras = this.numBoneInfluencers > 4;
  31220. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31221. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31222. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31223. var tempVector = BABYLON.Tmp.Vector3[0];
  31224. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31225. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31226. var matWeightIdx = 0;
  31227. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31228. finalMatrix.reset();
  31229. var inf;
  31230. var weight;
  31231. for (inf = 0; inf < 4; inf++) {
  31232. weight = matricesWeightsData[matWeightIdx + inf];
  31233. if (weight <= 0)
  31234. break;
  31235. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31236. finalMatrix.addToSelf(tempMatrix);
  31237. }
  31238. if (needExtras) {
  31239. for (inf = 0; inf < 4; inf++) {
  31240. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31241. if (weight <= 0)
  31242. break;
  31243. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31244. finalMatrix.addToSelf(tempMatrix);
  31245. }
  31246. }
  31247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31248. tempVector.toArray(data, index);
  31249. }
  31250. }
  31251. }
  31252. return data;
  31253. };
  31254. Mesh.prototype._createGlobalSubMesh = function (force) {
  31255. var totalVertices = this.getTotalVertices();
  31256. if (!totalVertices || !this.getIndices()) {
  31257. return null;
  31258. }
  31259. // Check if we need to recreate the submeshes
  31260. if (this.subMeshes && this.subMeshes.length > 0) {
  31261. var ib = this.getIndices();
  31262. if (!ib) {
  31263. return null;
  31264. }
  31265. var totalIndices = ib.length;
  31266. var needToRecreate = false;
  31267. if (force) {
  31268. needToRecreate = true;
  31269. }
  31270. else {
  31271. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31272. var submesh = _a[_i];
  31273. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31274. needToRecreate = true;
  31275. break;
  31276. }
  31277. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31278. needToRecreate = true;
  31279. break;
  31280. }
  31281. }
  31282. }
  31283. if (!needToRecreate) {
  31284. return this.subMeshes[0];
  31285. }
  31286. }
  31287. this.releaseSubMeshes();
  31288. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31289. };
  31290. Mesh.prototype.subdivide = function (count) {
  31291. if (count < 1) {
  31292. return;
  31293. }
  31294. var totalIndices = this.getTotalIndices();
  31295. var subdivisionSize = (totalIndices / count) | 0;
  31296. var offset = 0;
  31297. // Ensure that subdivisionSize is a multiple of 3
  31298. while (subdivisionSize % 3 !== 0) {
  31299. subdivisionSize++;
  31300. }
  31301. this.releaseSubMeshes();
  31302. for (var index = 0; index < count; index++) {
  31303. if (offset >= totalIndices) {
  31304. break;
  31305. }
  31306. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31307. offset += subdivisionSize;
  31308. }
  31309. this.synchronizeInstances();
  31310. };
  31311. /**
  31312. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31313. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31314. * The `data` are either a numeric array either a Float32Array.
  31315. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31316. * 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).
  31317. * Note that a new underlying VertexBuffer object is created each call.
  31318. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31319. *
  31320. * Possible `kind` values :
  31321. * - BABYLON.VertexBuffer.PositionKind
  31322. * - BABYLON.VertexBuffer.UVKind
  31323. * - BABYLON.VertexBuffer.UV2Kind
  31324. * - BABYLON.VertexBuffer.UV3Kind
  31325. * - BABYLON.VertexBuffer.UV4Kind
  31326. * - BABYLON.VertexBuffer.UV5Kind
  31327. * - BABYLON.VertexBuffer.UV6Kind
  31328. * - BABYLON.VertexBuffer.ColorKind
  31329. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31330. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31331. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31332. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31333. *
  31334. * Returns the Mesh.
  31335. */
  31336. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31337. if (updatable === void 0) { updatable = false; }
  31338. if (!this._geometry) {
  31339. var vertexData = new BABYLON.VertexData();
  31340. vertexData.set(data, kind);
  31341. var scene = this.getScene();
  31342. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31343. }
  31344. else {
  31345. this._geometry.setVerticesData(kind, data, updatable, stride);
  31346. }
  31347. return this;
  31348. };
  31349. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31350. if (updatable === void 0) { updatable = true; }
  31351. var vb = this.getVertexBuffer(kind);
  31352. if (!vb || vb.isUpdatable() === updatable) {
  31353. return;
  31354. }
  31355. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31356. };
  31357. /**
  31358. * Sets the mesh VertexBuffer.
  31359. * Returns the Mesh.
  31360. */
  31361. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31362. if (!this._geometry) {
  31363. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31364. }
  31365. this._geometry.setVerticesBuffer(buffer);
  31366. return this;
  31367. };
  31368. /**
  31369. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31370. * If the mesh has no geometry, it is simply returned as it is.
  31371. * The `data` are either a numeric array either a Float32Array.
  31372. * No new underlying VertexBuffer object is created.
  31373. * 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.
  31374. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31375. *
  31376. * Possible `kind` values :
  31377. * - BABYLON.VertexBuffer.PositionKind
  31378. * - BABYLON.VertexBuffer.UVKind
  31379. * - BABYLON.VertexBuffer.UV2Kind
  31380. * - BABYLON.VertexBuffer.UV3Kind
  31381. * - BABYLON.VertexBuffer.UV4Kind
  31382. * - BABYLON.VertexBuffer.UV5Kind
  31383. * - BABYLON.VertexBuffer.UV6Kind
  31384. * - BABYLON.VertexBuffer.ColorKind
  31385. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31386. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31387. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31388. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31389. *
  31390. * Returns the Mesh.
  31391. */
  31392. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31393. if (!this._geometry) {
  31394. return this;
  31395. }
  31396. if (!makeItUnique) {
  31397. this._geometry.updateVerticesData(kind, data, updateExtends);
  31398. }
  31399. else {
  31400. this.makeGeometryUnique();
  31401. this.updateVerticesData(kind, data, updateExtends, false);
  31402. }
  31403. return this;
  31404. };
  31405. /**
  31406. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31407. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31408. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31409. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31410. * Returns the Mesh.
  31411. */
  31412. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31413. if (computeNormals === void 0) { computeNormals = true; }
  31414. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31415. if (!positions) {
  31416. return this;
  31417. }
  31418. positionFunction(positions);
  31419. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31420. if (computeNormals) {
  31421. var indices = this.getIndices();
  31422. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31423. if (!normals) {
  31424. return this;
  31425. }
  31426. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31427. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31428. }
  31429. return this;
  31430. };
  31431. /**
  31432. * Creates a un-shared specific occurence of the geometry for the mesh.
  31433. * Returns the Mesh.
  31434. */
  31435. Mesh.prototype.makeGeometryUnique = function () {
  31436. if (!this._geometry) {
  31437. return this;
  31438. }
  31439. var oldGeometry = this._geometry;
  31440. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31441. oldGeometry.releaseForMesh(this, true);
  31442. geometry.applyToMesh(this);
  31443. return this;
  31444. };
  31445. /**
  31446. * Sets the mesh indices.
  31447. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31448. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31449. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31450. * This method creates a new index buffer each call.
  31451. * Returns the Mesh.
  31452. */
  31453. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31454. if (totalVertices === void 0) { totalVertices = null; }
  31455. if (updatable === void 0) { updatable = false; }
  31456. if (!this._geometry) {
  31457. var vertexData = new BABYLON.VertexData();
  31458. vertexData.indices = indices;
  31459. var scene = this.getScene();
  31460. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31461. }
  31462. else {
  31463. this._geometry.setIndices(indices, totalVertices, updatable);
  31464. }
  31465. return this;
  31466. };
  31467. /**
  31468. * Update the current index buffer
  31469. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31470. * Returns the Mesh.
  31471. */
  31472. Mesh.prototype.updateIndices = function (indices, offset) {
  31473. if (!this._geometry) {
  31474. return this;
  31475. }
  31476. this._geometry.updateIndices(indices, offset);
  31477. return this;
  31478. };
  31479. /**
  31480. * Invert the geometry to move from a right handed system to a left handed one.
  31481. * Returns the Mesh.
  31482. */
  31483. Mesh.prototype.toLeftHanded = function () {
  31484. if (!this._geometry) {
  31485. return this;
  31486. }
  31487. this._geometry.toLeftHanded();
  31488. return this;
  31489. };
  31490. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31491. if (!this._geometry) {
  31492. return this;
  31493. }
  31494. var engine = this.getScene().getEngine();
  31495. // Wireframe
  31496. var indexToBind;
  31497. if (this._unIndexed) {
  31498. indexToBind = null;
  31499. }
  31500. else {
  31501. switch (fillMode) {
  31502. case BABYLON.Material.PointFillMode:
  31503. indexToBind = null;
  31504. break;
  31505. case BABYLON.Material.WireFrameFillMode:
  31506. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31507. break;
  31508. default:
  31509. case BABYLON.Material.TriangleFillMode:
  31510. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31511. break;
  31512. }
  31513. }
  31514. // VBOs
  31515. this._geometry._bind(effect, indexToBind);
  31516. return this;
  31517. };
  31518. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31519. if (alternate === void 0) { alternate = false; }
  31520. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31521. return this;
  31522. }
  31523. this.onBeforeDrawObservable.notifyObservers(this);
  31524. var scene = this.getScene();
  31525. var engine = scene.getEngine();
  31526. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31527. // or triangles as points
  31528. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31529. }
  31530. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31531. // Triangles as wireframe
  31532. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31533. }
  31534. else {
  31535. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31536. }
  31537. if (scene._isAlternateRenderingEnabled && !alternate) {
  31538. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31539. if (!effect || !scene.activeCamera) {
  31540. return this;
  31541. }
  31542. scene._switchToAlternateCameraConfiguration(true);
  31543. this._effectiveMaterial.bindView(effect);
  31544. this._effectiveMaterial.bindViewProjection(effect);
  31545. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31546. this._draw(subMesh, fillMode, instancesCount, true);
  31547. engine.setViewport(scene.activeCamera.viewport);
  31548. scene._switchToAlternateCameraConfiguration(false);
  31549. this._effectiveMaterial.bindView(effect);
  31550. this._effectiveMaterial.bindViewProjection(effect);
  31551. }
  31552. return this;
  31553. };
  31554. /**
  31555. * Registers for this mesh a javascript function called just before the rendering process.
  31556. * This function is passed the current mesh.
  31557. * Return the Mesh.
  31558. */
  31559. Mesh.prototype.registerBeforeRender = function (func) {
  31560. this.onBeforeRenderObservable.add(func);
  31561. return this;
  31562. };
  31563. /**
  31564. * Disposes a previously registered javascript function called before the rendering.
  31565. * This function is passed the current mesh.
  31566. * Returns the Mesh.
  31567. */
  31568. Mesh.prototype.unregisterBeforeRender = function (func) {
  31569. this.onBeforeRenderObservable.removeCallback(func);
  31570. return this;
  31571. };
  31572. /**
  31573. * Registers for this mesh a javascript function called just after the rendering is complete.
  31574. * This function is passed the current mesh.
  31575. * Returns the Mesh.
  31576. */
  31577. Mesh.prototype.registerAfterRender = function (func) {
  31578. this.onAfterRenderObservable.add(func);
  31579. return this;
  31580. };
  31581. /**
  31582. * Disposes a previously registered javascript function called after the rendering.
  31583. * This function is passed the current mesh.
  31584. * Return the Mesh.
  31585. */
  31586. Mesh.prototype.unregisterAfterRender = function (func) {
  31587. this.onAfterRenderObservable.removeCallback(func);
  31588. return this;
  31589. };
  31590. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31591. var scene = this.getScene();
  31592. this._batchCache.mustReturn = false;
  31593. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31594. this._batchCache.visibleInstances[subMeshId] = null;
  31595. if (this._visibleInstances) {
  31596. var currentRenderId = scene.getRenderId();
  31597. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31598. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31599. var selfRenderId = this._renderId;
  31600. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31601. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31602. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31603. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31604. }
  31605. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31606. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31607. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31608. this._batchCache.mustReturn = true;
  31609. return this._batchCache;
  31610. }
  31611. if (currentRenderId !== selfRenderId) {
  31612. this._batchCache.renderSelf[subMeshId] = false;
  31613. }
  31614. }
  31615. this._renderIdForInstances[subMeshId] = currentRenderId;
  31616. }
  31617. return this._batchCache;
  31618. };
  31619. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31620. var visibleInstances = batch.visibleInstances[subMesh._id];
  31621. if (!visibleInstances) {
  31622. return this;
  31623. }
  31624. var matricesCount = visibleInstances.length + 1;
  31625. var bufferSize = matricesCount * 16 * 4;
  31626. var currentInstancesBufferSize = this._instancesBufferSize;
  31627. var instancesBuffer = this._instancesBuffer;
  31628. while (this._instancesBufferSize < bufferSize) {
  31629. this._instancesBufferSize *= 2;
  31630. }
  31631. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31632. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31633. }
  31634. var offset = 0;
  31635. var instancesCount = 0;
  31636. var world = this.getWorldMatrix();
  31637. if (batch.renderSelf[subMesh._id]) {
  31638. world.copyToArray(this._instancesData, offset);
  31639. offset += 16;
  31640. instancesCount++;
  31641. }
  31642. if (visibleInstances) {
  31643. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31644. var instance = visibleInstances[instanceIndex];
  31645. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31646. offset += 16;
  31647. instancesCount++;
  31648. }
  31649. }
  31650. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31651. if (instancesBuffer) {
  31652. instancesBuffer.dispose();
  31653. }
  31654. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31655. this._instancesBuffer = instancesBuffer;
  31656. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31657. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31658. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31659. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31660. }
  31661. else {
  31662. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31663. }
  31664. this._bind(subMesh, effect, fillMode);
  31665. this._draw(subMesh, fillMode, instancesCount);
  31666. engine.unbindInstanceAttributes();
  31667. return this;
  31668. };
  31669. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31670. var scene = this.getScene();
  31671. var engine = scene.getEngine();
  31672. if (hardwareInstancedRendering) {
  31673. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31674. }
  31675. else {
  31676. if (batch.renderSelf[subMesh._id]) {
  31677. // Draw
  31678. if (onBeforeDraw) {
  31679. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31680. }
  31681. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31682. }
  31683. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31684. if (visibleInstancesForSubMesh) {
  31685. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31686. var instance = visibleInstancesForSubMesh[instanceIndex];
  31687. // World
  31688. var world = instance.getWorldMatrix();
  31689. if (onBeforeDraw) {
  31690. onBeforeDraw(true, world, effectiveMaterial);
  31691. }
  31692. // Draw
  31693. this._draw(subMesh, fillMode);
  31694. }
  31695. }
  31696. }
  31697. return this;
  31698. };
  31699. /**
  31700. * Triggers the draw call for the mesh.
  31701. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31702. * Returns the Mesh.
  31703. */
  31704. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31705. this.checkOcclusionQuery();
  31706. if (this._isOccluded) {
  31707. return this;
  31708. }
  31709. var scene = this.getScene();
  31710. // Managing instances
  31711. var batch = this._getInstancesRenderList(subMesh._id);
  31712. if (batch.mustReturn) {
  31713. return this;
  31714. }
  31715. // Checking geometry state
  31716. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31717. return this;
  31718. }
  31719. this.onBeforeRenderObservable.notifyObservers(this);
  31720. var engine = scene.getEngine();
  31721. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31722. // Material
  31723. var material = subMesh.getMaterial();
  31724. if (!material) {
  31725. return this;
  31726. }
  31727. this._effectiveMaterial = material;
  31728. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31729. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31730. return this;
  31731. }
  31732. }
  31733. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31734. return this;
  31735. }
  31736. // Alpha mode
  31737. if (enableAlphaMode) {
  31738. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31739. }
  31740. // Outline - step 1
  31741. var savedDepthWrite = engine.getDepthWrite();
  31742. if (this.renderOutline) {
  31743. engine.setDepthWrite(false);
  31744. scene.getOutlineRenderer().render(subMesh, batch);
  31745. engine.setDepthWrite(savedDepthWrite);
  31746. }
  31747. var effect;
  31748. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31749. effect = subMesh.effect;
  31750. }
  31751. else {
  31752. effect = this._effectiveMaterial.getEffect();
  31753. }
  31754. if (!effect) {
  31755. return this;
  31756. }
  31757. var sideOrientation = this.overrideMaterialSideOrientation;
  31758. if (sideOrientation == null) {
  31759. sideOrientation = this._effectiveMaterial.sideOrientation;
  31760. if (this._getWorldMatrixDeterminant() < 0) {
  31761. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31762. }
  31763. }
  31764. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31765. if (this._effectiveMaterial.forceDepthWrite) {
  31766. engine.setDepthWrite(true);
  31767. }
  31768. // Bind
  31769. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31770. if (!hardwareInstancedRendering) {
  31771. this._bind(subMesh, effect, fillMode);
  31772. }
  31773. var world = this.getWorldMatrix();
  31774. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31775. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31776. }
  31777. else {
  31778. this._effectiveMaterial.bind(world, this);
  31779. }
  31780. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31781. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31782. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31783. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31784. }
  31785. // Draw
  31786. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31787. // Unbind
  31788. this._effectiveMaterial.unbind();
  31789. // Outline - step 2
  31790. if (this.renderOutline && savedDepthWrite) {
  31791. engine.setDepthWrite(true);
  31792. engine.setColorWrite(false);
  31793. scene.getOutlineRenderer().render(subMesh, batch);
  31794. engine.setColorWrite(true);
  31795. }
  31796. // Overlay
  31797. if (this.renderOverlay) {
  31798. var currentMode = engine.getAlphaMode();
  31799. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31800. scene.getOutlineRenderer().render(subMesh, batch, true);
  31801. engine.setAlphaMode(currentMode);
  31802. }
  31803. this.onAfterRenderObservable.notifyObservers(this);
  31804. return this;
  31805. };
  31806. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31807. if (isInstance && effectiveMaterial) {
  31808. effectiveMaterial.bindOnlyWorldMatrix(world);
  31809. }
  31810. };
  31811. /**
  31812. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31813. */
  31814. Mesh.prototype.getEmittedParticleSystems = function () {
  31815. var results = new Array();
  31816. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31817. var particleSystem = this.getScene().particleSystems[index];
  31818. if (particleSystem.emitter === this) {
  31819. results.push(particleSystem);
  31820. }
  31821. }
  31822. return results;
  31823. };
  31824. /**
  31825. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31826. */
  31827. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31828. var results = new Array();
  31829. var descendants = this.getDescendants();
  31830. descendants.push(this);
  31831. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31832. var particleSystem = this.getScene().particleSystems[index];
  31833. var emitter = particleSystem.emitter;
  31834. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31835. results.push(particleSystem);
  31836. }
  31837. }
  31838. return results;
  31839. };
  31840. Mesh.prototype._checkDelayState = function () {
  31841. var scene = this.getScene();
  31842. if (this._geometry) {
  31843. this._geometry.load(scene);
  31844. }
  31845. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31846. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31847. this._queueLoad(scene);
  31848. }
  31849. return this;
  31850. };
  31851. Mesh.prototype._queueLoad = function (scene) {
  31852. var _this = this;
  31853. scene._addPendingData(this);
  31854. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31855. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31856. if (data instanceof ArrayBuffer) {
  31857. _this._delayLoadingFunction(data, _this);
  31858. }
  31859. else {
  31860. _this._delayLoadingFunction(JSON.parse(data), _this);
  31861. }
  31862. _this.instances.forEach(function (instance) {
  31863. instance._syncSubMeshes();
  31864. });
  31865. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31866. scene._removePendingData(_this);
  31867. }, function () { }, scene.database, getBinaryData);
  31868. return this;
  31869. };
  31870. /**
  31871. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31872. */
  31873. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31874. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31875. return false;
  31876. }
  31877. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31878. return false;
  31879. }
  31880. this._checkDelayState();
  31881. return true;
  31882. };
  31883. /**
  31884. * Sets the mesh material by the material or multiMaterial `id` property.
  31885. * The material `id` is a string identifying the material or the multiMaterial.
  31886. * This method returns the Mesh.
  31887. */
  31888. Mesh.prototype.setMaterialByID = function (id) {
  31889. var materials = this.getScene().materials;
  31890. var index;
  31891. for (index = materials.length - 1; index > -1; index--) {
  31892. if (materials[index].id === id) {
  31893. this.material = materials[index];
  31894. return this;
  31895. }
  31896. }
  31897. // Multi
  31898. var multiMaterials = this.getScene().multiMaterials;
  31899. for (index = multiMaterials.length - 1; index > -1; index--) {
  31900. if (multiMaterials[index].id === id) {
  31901. this.material = multiMaterials[index];
  31902. return this;
  31903. }
  31904. }
  31905. return this;
  31906. };
  31907. /**
  31908. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31909. */
  31910. Mesh.prototype.getAnimatables = function () {
  31911. var results = new Array();
  31912. if (this.material) {
  31913. results.push(this.material);
  31914. }
  31915. if (this.skeleton) {
  31916. results.push(this.skeleton);
  31917. }
  31918. return results;
  31919. };
  31920. /**
  31921. * Modifies the mesh geometry according to the passed transformation matrix.
  31922. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31923. * The mesh normals are modified accordingly the same transformation.
  31924. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31925. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31926. * Returns the Mesh.
  31927. */
  31928. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31929. // Position
  31930. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31931. return this;
  31932. }
  31933. var submeshes = this.subMeshes.splice(0);
  31934. this._resetPointsArrayCache();
  31935. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31936. var temp = new Array();
  31937. var index;
  31938. for (index = 0; index < data.length; index += 3) {
  31939. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31940. }
  31941. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31942. // Normals
  31943. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31944. return this;
  31945. }
  31946. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31947. temp = [];
  31948. for (index = 0; index < data.length; index += 3) {
  31949. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31950. }
  31951. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31952. // flip faces?
  31953. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31954. this.flipFaces();
  31955. }
  31956. // Restore submeshes
  31957. this.releaseSubMeshes();
  31958. this.subMeshes = submeshes;
  31959. return this;
  31960. };
  31961. /**
  31962. * Modifies the mesh geometry according to its own current World Matrix.
  31963. * The mesh World Matrix is then reset.
  31964. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31965. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31966. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31967. * Returns the Mesh.
  31968. */
  31969. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31970. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31971. this.scaling.copyFromFloats(1, 1, 1);
  31972. this.position.copyFromFloats(0, 0, 0);
  31973. this.rotation.copyFromFloats(0, 0, 0);
  31974. //only if quaternion is already set
  31975. if (this.rotationQuaternion) {
  31976. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31977. }
  31978. this._worldMatrix = BABYLON.Matrix.Identity();
  31979. return this;
  31980. };
  31981. Object.defineProperty(Mesh.prototype, "_positions", {
  31982. // Cache
  31983. get: function () {
  31984. if (this._geometry) {
  31985. return this._geometry._positions;
  31986. }
  31987. return null;
  31988. },
  31989. enumerable: true,
  31990. configurable: true
  31991. });
  31992. Mesh.prototype._resetPointsArrayCache = function () {
  31993. if (this._geometry) {
  31994. this._geometry._resetPointsArrayCache();
  31995. }
  31996. return this;
  31997. };
  31998. Mesh.prototype._generatePointsArray = function () {
  31999. if (this._geometry) {
  32000. return this._geometry._generatePointsArray();
  32001. }
  32002. return false;
  32003. };
  32004. /**
  32005. * Returns a new Mesh object generated from the current mesh properties.
  32006. * This method must not get confused with createInstance().
  32007. * The parameter `name` is a string, the name given to the new mesh.
  32008. * The optional parameter `newParent` can be any Node object (default `null`).
  32009. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32010. * 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.
  32011. */
  32012. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32013. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32014. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32015. };
  32016. /**
  32017. * Releases resources associated with this mesh.
  32018. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32019. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32020. */
  32021. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32022. var _this = this;
  32023. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32024. this.morphTargetManager = null;
  32025. if (this._geometry) {
  32026. this._geometry.releaseForMesh(this, true);
  32027. }
  32028. // Sources
  32029. var meshes = this.getScene().meshes;
  32030. meshes.forEach(function (abstractMesh) {
  32031. var mesh = abstractMesh;
  32032. if (mesh._source && mesh._source === _this) {
  32033. mesh._source = null;
  32034. }
  32035. });
  32036. this._source = null;
  32037. // Instances
  32038. if (this._instancesBuffer) {
  32039. this._instancesBuffer.dispose();
  32040. this._instancesBuffer = null;
  32041. }
  32042. while (this.instances.length) {
  32043. this.instances[0].dispose();
  32044. }
  32045. // Effect layers.
  32046. var effectLayers = this.getScene().effectLayers;
  32047. for (var i = 0; i < effectLayers.length; i++) {
  32048. var effectLayer = effectLayers[i];
  32049. if (effectLayer) {
  32050. effectLayer._disposeMesh(this);
  32051. }
  32052. }
  32053. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32054. };
  32055. /**
  32056. * Modifies the mesh geometry according to a displacement map.
  32057. * 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.
  32058. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32059. * This method returns nothing.
  32060. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32061. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32062. * 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.
  32063. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32064. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32065. *
  32066. * Returns the Mesh.
  32067. */
  32068. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32069. var _this = this;
  32070. var scene = this.getScene();
  32071. var onload = function (img) {
  32072. // Getting height map data
  32073. var canvas = document.createElement("canvas");
  32074. var context = canvas.getContext("2d");
  32075. var heightMapWidth = img.width;
  32076. var heightMapHeight = img.height;
  32077. canvas.width = heightMapWidth;
  32078. canvas.height = heightMapHeight;
  32079. context.drawImage(img, 0, 0);
  32080. // Create VertexData from map data
  32081. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32082. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32083. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32084. //execute success callback, if set
  32085. if (onSuccess) {
  32086. onSuccess(_this);
  32087. }
  32088. };
  32089. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32090. return this;
  32091. };
  32092. /**
  32093. * Modifies the mesh geometry according to a displacementMap buffer.
  32094. * 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.
  32095. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32096. * This method returns nothing.
  32097. * 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.
  32098. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32099. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32100. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32101. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32102. *
  32103. * Returns the Mesh.
  32104. */
  32105. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32106. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32107. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32108. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32109. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32110. return this;
  32111. }
  32112. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32113. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32114. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32115. var position = BABYLON.Vector3.Zero();
  32116. var normal = BABYLON.Vector3.Zero();
  32117. var uv = BABYLON.Vector2.Zero();
  32118. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32119. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32120. for (var index = 0; index < positions.length; index += 3) {
  32121. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32122. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32123. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32124. // Compute height
  32125. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32126. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32127. var pos = (u + v * heightMapWidth) * 4;
  32128. var r = buffer[pos] / 255.0;
  32129. var g = buffer[pos + 1] / 255.0;
  32130. var b = buffer[pos + 2] / 255.0;
  32131. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32132. normal.normalize();
  32133. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32134. position = position.add(normal);
  32135. position.toArray(positions, index);
  32136. }
  32137. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32138. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32139. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32140. return this;
  32141. };
  32142. /**
  32143. * Modify the mesh to get a flat shading rendering.
  32144. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32145. * This method returns the Mesh.
  32146. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32147. */
  32148. Mesh.prototype.convertToFlatShadedMesh = function () {
  32149. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32150. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32151. var kinds = this.getVerticesDataKinds();
  32152. var vbs = {};
  32153. var data = {};
  32154. var newdata = {};
  32155. var updatableNormals = false;
  32156. var kindIndex;
  32157. var kind;
  32158. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32159. kind = kinds[kindIndex];
  32160. var vertexBuffer = this.getVertexBuffer(kind);
  32161. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32162. updatableNormals = vertexBuffer.isUpdatable();
  32163. kinds.splice(kindIndex, 1);
  32164. kindIndex--;
  32165. continue;
  32166. }
  32167. vbs[kind] = vertexBuffer;
  32168. data[kind] = vbs[kind].getData();
  32169. newdata[kind] = [];
  32170. }
  32171. // Save previous submeshes
  32172. var previousSubmeshes = this.subMeshes.slice(0);
  32173. var indices = this.getIndices();
  32174. var totalIndices = this.getTotalIndices();
  32175. // Generating unique vertices per face
  32176. var index;
  32177. for (index = 0; index < totalIndices; index++) {
  32178. var vertexIndex = indices[index];
  32179. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32180. kind = kinds[kindIndex];
  32181. var stride = vbs[kind].getStrideSize();
  32182. for (var offset = 0; offset < stride; offset++) {
  32183. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32184. }
  32185. }
  32186. }
  32187. // Updating faces & normal
  32188. var normals = [];
  32189. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32190. for (index = 0; index < totalIndices; index += 3) {
  32191. indices[index] = index;
  32192. indices[index + 1] = index + 1;
  32193. indices[index + 2] = index + 2;
  32194. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32195. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32196. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32197. var p1p2 = p1.subtract(p2);
  32198. var p3p2 = p3.subtract(p2);
  32199. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32200. // Store same normals for every vertex
  32201. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32202. normals.push(normal.x);
  32203. normals.push(normal.y);
  32204. normals.push(normal.z);
  32205. }
  32206. }
  32207. this.setIndices(indices);
  32208. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32209. // Updating vertex buffers
  32210. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32211. kind = kinds[kindIndex];
  32212. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32213. }
  32214. // Updating submeshes
  32215. this.releaseSubMeshes();
  32216. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32217. var previousOne = previousSubmeshes[submeshIndex];
  32218. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32219. }
  32220. this.synchronizeInstances();
  32221. return this;
  32222. };
  32223. /**
  32224. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32225. * In other words, more vertices, no more indices and a single bigger VBO.
  32226. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32227. * Returns the Mesh.
  32228. */
  32229. Mesh.prototype.convertToUnIndexedMesh = function () {
  32230. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32231. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32232. var kinds = this.getVerticesDataKinds();
  32233. var vbs = {};
  32234. var data = {};
  32235. var newdata = {};
  32236. var kindIndex;
  32237. var kind;
  32238. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32239. kind = kinds[kindIndex];
  32240. var vertexBuffer = this.getVertexBuffer(kind);
  32241. vbs[kind] = vertexBuffer;
  32242. data[kind] = vbs[kind].getData();
  32243. newdata[kind] = [];
  32244. }
  32245. // Save previous submeshes
  32246. var previousSubmeshes = this.subMeshes.slice(0);
  32247. var indices = this.getIndices();
  32248. var totalIndices = this.getTotalIndices();
  32249. // Generating unique vertices per face
  32250. var index;
  32251. for (index = 0; index < totalIndices; index++) {
  32252. var vertexIndex = indices[index];
  32253. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32254. kind = kinds[kindIndex];
  32255. var stride = vbs[kind].getStrideSize();
  32256. for (var offset = 0; offset < stride; offset++) {
  32257. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32258. }
  32259. }
  32260. }
  32261. // Updating indices
  32262. for (index = 0; index < totalIndices; index += 3) {
  32263. indices[index] = index;
  32264. indices[index + 1] = index + 1;
  32265. indices[index + 2] = index + 2;
  32266. }
  32267. this.setIndices(indices);
  32268. // Updating vertex buffers
  32269. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32270. kind = kinds[kindIndex];
  32271. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32272. }
  32273. // Updating submeshes
  32274. this.releaseSubMeshes();
  32275. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32276. var previousOne = previousSubmeshes[submeshIndex];
  32277. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32278. }
  32279. this._unIndexed = true;
  32280. this.synchronizeInstances();
  32281. return this;
  32282. };
  32283. /**
  32284. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32285. * This method returns the Mesh.
  32286. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32287. */
  32288. Mesh.prototype.flipFaces = function (flipNormals) {
  32289. if (flipNormals === void 0) { flipNormals = false; }
  32290. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32291. var i;
  32292. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32293. for (i = 0; i < vertex_data.normals.length; i++) {
  32294. vertex_data.normals[i] *= -1;
  32295. }
  32296. }
  32297. if (vertex_data.indices) {
  32298. var temp;
  32299. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32300. // reassign indices
  32301. temp = vertex_data.indices[i + 1];
  32302. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32303. vertex_data.indices[i + 2] = temp;
  32304. }
  32305. }
  32306. vertex_data.applyToMesh(this);
  32307. return this;
  32308. };
  32309. // Instances
  32310. /**
  32311. * Creates a new InstancedMesh object from the mesh model.
  32312. * An instance shares the same properties and the same material than its model.
  32313. * Only these properties of each instance can then be set individually :
  32314. * - position
  32315. * - rotation
  32316. * - rotationQuaternion
  32317. * - setPivotMatrix
  32318. * - scaling
  32319. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32320. * Warning : this method is not supported for Line mesh and LineSystem
  32321. */
  32322. Mesh.prototype.createInstance = function (name) {
  32323. return new BABYLON.InstancedMesh(name, this);
  32324. };
  32325. /**
  32326. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32327. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32328. * This method returns the Mesh.
  32329. */
  32330. Mesh.prototype.synchronizeInstances = function () {
  32331. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32332. var instance = this.instances[instanceIndex];
  32333. instance._syncSubMeshes();
  32334. }
  32335. return this;
  32336. };
  32337. /**
  32338. * Simplify the mesh according to the given array of settings.
  32339. * Function will return immediately and will simplify async. It returns the Mesh.
  32340. * @param settings a collection of simplification settings.
  32341. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32342. * @param type the type of simplification to run.
  32343. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32344. */
  32345. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32346. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32347. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32348. this.getScene().simplificationQueue.addTask({
  32349. settings: settings,
  32350. parallelProcessing: parallelProcessing,
  32351. mesh: this,
  32352. simplificationType: simplificationType,
  32353. successCallback: successCallback
  32354. });
  32355. return this;
  32356. };
  32357. /**
  32358. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32359. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32360. * This should be used together with the simplification to avoid disappearing triangles.
  32361. * Returns the Mesh.
  32362. * @param successCallback an optional success callback to be called after the optimization finished.
  32363. */
  32364. Mesh.prototype.optimizeIndices = function (successCallback) {
  32365. var _this = this;
  32366. var indices = this.getIndices();
  32367. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32368. if (!positions || !indices) {
  32369. return this;
  32370. }
  32371. var vectorPositions = new Array();
  32372. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32373. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32374. }
  32375. var dupes = new Array();
  32376. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32377. var realPos = vectorPositions.length - 1 - iteration;
  32378. var testedPosition = vectorPositions[realPos];
  32379. for (var j = 0; j < realPos; ++j) {
  32380. var againstPosition = vectorPositions[j];
  32381. if (testedPosition.equals(againstPosition)) {
  32382. dupes[realPos] = j;
  32383. break;
  32384. }
  32385. }
  32386. }, function () {
  32387. for (var i = 0; i < indices.length; ++i) {
  32388. indices[i] = dupes[indices[i]] || indices[i];
  32389. }
  32390. //indices are now reordered
  32391. var originalSubMeshes = _this.subMeshes.slice(0);
  32392. _this.setIndices(indices);
  32393. _this.subMeshes = originalSubMeshes;
  32394. if (successCallback) {
  32395. successCallback(_this);
  32396. }
  32397. });
  32398. return this;
  32399. };
  32400. Mesh.prototype.serialize = function (serializationObject) {
  32401. serializationObject.name = this.name;
  32402. serializationObject.id = this.id;
  32403. serializationObject.type = this.getClassName();
  32404. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32405. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32406. }
  32407. serializationObject.position = this.position.asArray();
  32408. if (this.rotationQuaternion) {
  32409. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32410. }
  32411. else if (this.rotation) {
  32412. serializationObject.rotation = this.rotation.asArray();
  32413. }
  32414. serializationObject.scaling = this.scaling.asArray();
  32415. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32416. serializationObject.isEnabled = this.isEnabled(false);
  32417. serializationObject.isVisible = this.isVisible;
  32418. serializationObject.infiniteDistance = this.infiniteDistance;
  32419. serializationObject.pickable = this.isPickable;
  32420. serializationObject.receiveShadows = this.receiveShadows;
  32421. serializationObject.billboardMode = this.billboardMode;
  32422. serializationObject.visibility = this.visibility;
  32423. serializationObject.checkCollisions = this.checkCollisions;
  32424. serializationObject.isBlocker = this.isBlocker;
  32425. // Parent
  32426. if (this.parent) {
  32427. serializationObject.parentId = this.parent.id;
  32428. }
  32429. // Geometry
  32430. serializationObject.isUnIndexed = this.isUnIndexed;
  32431. var geometry = this._geometry;
  32432. if (geometry) {
  32433. var geometryId = geometry.id;
  32434. serializationObject.geometryId = geometryId;
  32435. // SubMeshes
  32436. serializationObject.subMeshes = [];
  32437. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32438. var subMesh = this.subMeshes[subIndex];
  32439. serializationObject.subMeshes.push({
  32440. materialIndex: subMesh.materialIndex,
  32441. verticesStart: subMesh.verticesStart,
  32442. verticesCount: subMesh.verticesCount,
  32443. indexStart: subMesh.indexStart,
  32444. indexCount: subMesh.indexCount
  32445. });
  32446. }
  32447. }
  32448. // Material
  32449. if (this.material) {
  32450. serializationObject.materialId = this.material.id;
  32451. }
  32452. else {
  32453. this.material = null;
  32454. }
  32455. // Morph targets
  32456. if (this.morphTargetManager) {
  32457. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32458. }
  32459. // Skeleton
  32460. if (this.skeleton) {
  32461. serializationObject.skeletonId = this.skeleton.id;
  32462. }
  32463. // Physics
  32464. //TODO implement correct serialization for physics impostors.
  32465. var impostor = this.getPhysicsImpostor();
  32466. if (impostor) {
  32467. serializationObject.physicsMass = impostor.getParam("mass");
  32468. serializationObject.physicsFriction = impostor.getParam("friction");
  32469. serializationObject.physicsRestitution = impostor.getParam("mass");
  32470. serializationObject.physicsImpostor = impostor.type;
  32471. }
  32472. // Metadata
  32473. if (this.metadata) {
  32474. serializationObject.metadata = this.metadata;
  32475. }
  32476. // Instances
  32477. serializationObject.instances = [];
  32478. for (var index = 0; index < this.instances.length; index++) {
  32479. var instance = this.instances[index];
  32480. var serializationInstance = {
  32481. name: instance.name,
  32482. id: instance.id,
  32483. position: instance.position.asArray(),
  32484. scaling: instance.scaling.asArray()
  32485. };
  32486. if (instance.rotationQuaternion) {
  32487. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32488. }
  32489. else if (instance.rotation) {
  32490. serializationInstance.rotation = instance.rotation.asArray();
  32491. }
  32492. serializationObject.instances.push(serializationInstance);
  32493. // Animations
  32494. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32495. serializationInstance.ranges = instance.serializeAnimationRanges();
  32496. }
  32497. //
  32498. // Animations
  32499. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32500. serializationObject.ranges = this.serializeAnimationRanges();
  32501. // Layer mask
  32502. serializationObject.layerMask = this.layerMask;
  32503. // Alpha
  32504. serializationObject.alphaIndex = this.alphaIndex;
  32505. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32506. // Overlay
  32507. serializationObject.overlayAlpha = this.overlayAlpha;
  32508. serializationObject.overlayColor = this.overlayColor.asArray();
  32509. serializationObject.renderOverlay = this.renderOverlay;
  32510. // Fog
  32511. serializationObject.applyFog = this.applyFog;
  32512. // Action Manager
  32513. if (this.actionManager) {
  32514. serializationObject.actions = this.actionManager.serialize(this.name);
  32515. }
  32516. };
  32517. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32518. if (!this.geometry) {
  32519. return;
  32520. }
  32521. this._markSubMeshesAsAttributesDirty();
  32522. var morphTargetManager = this._morphTargetManager;
  32523. if (morphTargetManager && morphTargetManager.vertexCount) {
  32524. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32525. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32526. this.morphTargetManager = null;
  32527. return;
  32528. }
  32529. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32530. var morphTarget = morphTargetManager.getActiveTarget(index);
  32531. var positions = morphTarget.getPositions();
  32532. if (!positions) {
  32533. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32534. return;
  32535. }
  32536. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32537. var normals = morphTarget.getNormals();
  32538. if (normals) {
  32539. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32540. }
  32541. var tangents = morphTarget.getTangents();
  32542. if (tangents) {
  32543. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32544. }
  32545. }
  32546. }
  32547. else {
  32548. var index = 0;
  32549. // Positions
  32550. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32551. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32552. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32553. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32554. }
  32555. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32556. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32557. }
  32558. index++;
  32559. }
  32560. }
  32561. };
  32562. // Statics
  32563. /**
  32564. * Returns a new Mesh object parsed from the source provided.
  32565. * The parameter `parsedMesh` is the source.
  32566. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32567. */
  32568. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32569. var mesh;
  32570. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32571. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32572. }
  32573. else {
  32574. mesh = new Mesh(parsedMesh.name, scene);
  32575. }
  32576. mesh.id = parsedMesh.id;
  32577. if (BABYLON.Tags) {
  32578. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32579. }
  32580. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32581. if (parsedMesh.metadata !== undefined) {
  32582. mesh.metadata = parsedMesh.metadata;
  32583. }
  32584. if (parsedMesh.rotationQuaternion) {
  32585. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32586. }
  32587. else if (parsedMesh.rotation) {
  32588. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32589. }
  32590. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32591. if (parsedMesh.localMatrix) {
  32592. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32593. }
  32594. else if (parsedMesh.pivotMatrix) {
  32595. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32596. }
  32597. mesh.setEnabled(parsedMesh.isEnabled);
  32598. mesh.isVisible = parsedMesh.isVisible;
  32599. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32600. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32601. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32602. if (parsedMesh.applyFog !== undefined) {
  32603. mesh.applyFog = parsedMesh.applyFog;
  32604. }
  32605. if (parsedMesh.pickable !== undefined) {
  32606. mesh.isPickable = parsedMesh.pickable;
  32607. }
  32608. if (parsedMesh.alphaIndex !== undefined) {
  32609. mesh.alphaIndex = parsedMesh.alphaIndex;
  32610. }
  32611. mesh.receiveShadows = parsedMesh.receiveShadows;
  32612. mesh.billboardMode = parsedMesh.billboardMode;
  32613. if (parsedMesh.visibility !== undefined) {
  32614. mesh.visibility = parsedMesh.visibility;
  32615. }
  32616. mesh.checkCollisions = parsedMesh.checkCollisions;
  32617. if (parsedMesh.isBlocker !== undefined) {
  32618. mesh.isBlocker = parsedMesh.isBlocker;
  32619. }
  32620. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32621. // freezeWorldMatrix
  32622. if (parsedMesh.freezeWorldMatrix) {
  32623. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32624. }
  32625. // Parent
  32626. if (parsedMesh.parentId) {
  32627. mesh._waitingParentId = parsedMesh.parentId;
  32628. }
  32629. // Actions
  32630. if (parsedMesh.actions !== undefined) {
  32631. mesh._waitingActions = parsedMesh.actions;
  32632. }
  32633. // Overlay
  32634. if (parsedMesh.overlayAlpha !== undefined) {
  32635. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32636. }
  32637. if (parsedMesh.overlayColor !== undefined) {
  32638. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32639. }
  32640. if (parsedMesh.renderOverlay !== undefined) {
  32641. mesh.renderOverlay = parsedMesh.renderOverlay;
  32642. }
  32643. // Geometry
  32644. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32645. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32646. if (parsedMesh.delayLoadingFile) {
  32647. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32648. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32649. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32650. if (parsedMesh._binaryInfo) {
  32651. mesh._binaryInfo = parsedMesh._binaryInfo;
  32652. }
  32653. mesh._delayInfo = [];
  32654. if (parsedMesh.hasUVs) {
  32655. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32656. }
  32657. if (parsedMesh.hasUVs2) {
  32658. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32659. }
  32660. if (parsedMesh.hasUVs3) {
  32661. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32662. }
  32663. if (parsedMesh.hasUVs4) {
  32664. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32665. }
  32666. if (parsedMesh.hasUVs5) {
  32667. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32668. }
  32669. if (parsedMesh.hasUVs6) {
  32670. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32671. }
  32672. if (parsedMesh.hasColors) {
  32673. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32674. }
  32675. if (parsedMesh.hasMatricesIndices) {
  32676. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32677. }
  32678. if (parsedMesh.hasMatricesWeights) {
  32679. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32680. }
  32681. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32682. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32683. mesh._checkDelayState();
  32684. }
  32685. }
  32686. else {
  32687. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32688. }
  32689. // Material
  32690. if (parsedMesh.materialId) {
  32691. mesh.setMaterialByID(parsedMesh.materialId);
  32692. }
  32693. else {
  32694. mesh.material = null;
  32695. }
  32696. // Morph targets
  32697. if (parsedMesh.morphTargetManagerId > -1) {
  32698. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32699. }
  32700. // Skeleton
  32701. if (parsedMesh.skeletonId > -1) {
  32702. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32703. if (parsedMesh.numBoneInfluencers) {
  32704. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32705. }
  32706. }
  32707. // Animations
  32708. if (parsedMesh.animations) {
  32709. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32710. var parsedAnimation = parsedMesh.animations[animationIndex];
  32711. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32712. }
  32713. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32714. }
  32715. if (parsedMesh.autoAnimate) {
  32716. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32717. }
  32718. // Layer Mask
  32719. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32720. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32721. }
  32722. else {
  32723. mesh.layerMask = 0x0FFFFFFF;
  32724. }
  32725. // Physics
  32726. if (parsedMesh.physicsImpostor) {
  32727. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32728. mass: parsedMesh.physicsMass,
  32729. friction: parsedMesh.physicsFriction,
  32730. restitution: parsedMesh.physicsRestitution
  32731. }, scene);
  32732. }
  32733. // Instances
  32734. if (parsedMesh.instances) {
  32735. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32736. var parsedInstance = parsedMesh.instances[index];
  32737. var instance = mesh.createInstance(parsedInstance.name);
  32738. if (parsedInstance.id) {
  32739. instance.id = parsedInstance.id;
  32740. }
  32741. if (BABYLON.Tags) {
  32742. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32743. }
  32744. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32745. if (parsedInstance.parentId) {
  32746. instance._waitingParentId = parsedInstance.parentId;
  32747. }
  32748. if (parsedInstance.rotationQuaternion) {
  32749. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32750. }
  32751. else if (parsedInstance.rotation) {
  32752. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32753. }
  32754. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32755. instance.checkCollisions = mesh.checkCollisions;
  32756. if (parsedMesh.animations) {
  32757. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32758. parsedAnimation = parsedMesh.animations[animationIndex];
  32759. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32760. }
  32761. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32762. }
  32763. }
  32764. }
  32765. return mesh;
  32766. };
  32767. /**
  32768. * Creates a ribbon mesh.
  32769. * Please consider using the same method from the MeshBuilder class instead.
  32770. * 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.
  32771. *
  32772. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32773. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32774. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32775. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32776. * 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.
  32777. * 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.
  32778. * 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
  32779. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32780. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32782. */
  32783. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32784. if (closeArray === void 0) { closeArray = false; }
  32785. if (updatable === void 0) { updatable = false; }
  32786. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32787. pathArray: pathArray,
  32788. closeArray: closeArray,
  32789. closePath: closePath,
  32790. offset: offset,
  32791. updatable: updatable,
  32792. sideOrientation: sideOrientation,
  32793. instance: instance
  32794. }, scene);
  32795. };
  32796. /**
  32797. * Creates a plane polygonal mesh. By default, this is a disc.
  32798. * Please consider using the same method from the MeshBuilder class instead.
  32799. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32800. * 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.
  32801. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32802. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32804. */
  32805. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32806. if (scene === void 0) { scene = null; }
  32807. var options = {
  32808. radius: radius,
  32809. tessellation: tessellation,
  32810. sideOrientation: sideOrientation,
  32811. updatable: updatable
  32812. };
  32813. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32814. };
  32815. /**
  32816. * Creates a box mesh.
  32817. * Please consider using the same method from the MeshBuilder class instead.
  32818. * The parameter `size` sets the size (float) of each box side (default 1).
  32819. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32820. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32822. */
  32823. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32824. if (scene === void 0) { scene = null; }
  32825. var options = {
  32826. size: size,
  32827. sideOrientation: sideOrientation,
  32828. updatable: updatable
  32829. };
  32830. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32831. };
  32832. /**
  32833. * Creates a sphere mesh.
  32834. * Please consider using the same method from the MeshBuilder class instead.
  32835. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32836. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32840. */
  32841. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32842. var options = {
  32843. segments: segments,
  32844. diameterX: diameter,
  32845. diameterY: diameter,
  32846. diameterZ: diameter,
  32847. sideOrientation: sideOrientation,
  32848. updatable: updatable
  32849. };
  32850. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32851. };
  32852. /**
  32853. * Creates a cylinder or a cone mesh.
  32854. * Please consider using the same method from the MeshBuilder class instead.
  32855. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32856. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32857. * 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.
  32858. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32859. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32863. */
  32864. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32865. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32866. if (scene !== undefined) {
  32867. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32868. updatable = scene;
  32869. }
  32870. scene = subdivisions;
  32871. subdivisions = 1;
  32872. }
  32873. var options = {
  32874. height: height,
  32875. diameterTop: diameterTop,
  32876. diameterBottom: diameterBottom,
  32877. tessellation: tessellation,
  32878. subdivisions: subdivisions,
  32879. sideOrientation: sideOrientation,
  32880. updatable: updatable
  32881. };
  32882. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32883. };
  32884. // Torus (Code from SharpDX.org)
  32885. /**
  32886. * Creates a torus mesh.
  32887. * Please consider using the same method from the MeshBuilder class instead.
  32888. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32889. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32890. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32891. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32894. */
  32895. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32896. var options = {
  32897. diameter: diameter,
  32898. thickness: thickness,
  32899. tessellation: tessellation,
  32900. sideOrientation: sideOrientation,
  32901. updatable: updatable
  32902. };
  32903. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32904. };
  32905. /**
  32906. * Creates a torus knot mesh.
  32907. * Please consider using the same method from the MeshBuilder class instead.
  32908. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32909. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32910. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32911. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32912. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32913. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32914. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32915. */
  32916. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32917. var options = {
  32918. radius: radius,
  32919. tube: tube,
  32920. radialSegments: radialSegments,
  32921. tubularSegments: tubularSegments,
  32922. p: p,
  32923. q: q,
  32924. sideOrientation: sideOrientation,
  32925. updatable: updatable
  32926. };
  32927. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32928. };
  32929. /**
  32930. * Creates a line mesh.
  32931. * Please consider using the same method from the MeshBuilder class instead.
  32932. * 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.
  32933. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32934. * The parameter `points` is an array successive Vector3.
  32935. * 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
  32936. * When updating an instance, remember that only point positions can change, not the number of points.
  32937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32938. */
  32939. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32940. if (scene === void 0) { scene = null; }
  32941. if (updatable === void 0) { updatable = false; }
  32942. if (instance === void 0) { instance = null; }
  32943. var options = {
  32944. points: points,
  32945. updatable: updatable,
  32946. instance: instance
  32947. };
  32948. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32949. };
  32950. /**
  32951. * Creates a dashed line mesh.
  32952. * Please consider using the same method from the MeshBuilder class instead.
  32953. * 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.
  32954. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32955. * The parameter `points` is an array successive Vector3.
  32956. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32957. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32958. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32959. * 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
  32960. * When updating an instance, remember that only point positions can change, not the number of points.
  32961. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32962. */
  32963. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32964. if (scene === void 0) { scene = null; }
  32965. var options = {
  32966. points: points,
  32967. dashSize: dashSize,
  32968. gapSize: gapSize,
  32969. dashNb: dashNb,
  32970. updatable: updatable,
  32971. instance: instance
  32972. };
  32973. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32974. };
  32975. /**
  32976. * Creates a polygon mesh.
  32977. * Please consider using the same method from the MeshBuilder class instead.
  32978. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32979. * 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.
  32980. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32982. * Remember you can only change the shape positions, not their number when updating a polygon.
  32983. */
  32984. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32985. var options = {
  32986. shape: shape,
  32987. holes: holes,
  32988. updatable: updatable,
  32989. sideOrientation: sideOrientation
  32990. };
  32991. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32992. };
  32993. /**
  32994. * Creates an extruded polygon mesh, with depth in the Y direction.
  32995. * Please consider using the same method from the MeshBuilder class instead.
  32996. */
  32997. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32998. var options = {
  32999. shape: shape,
  33000. holes: holes,
  33001. depth: depth,
  33002. updatable: updatable,
  33003. sideOrientation: sideOrientation
  33004. };
  33005. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33006. };
  33007. /**
  33008. * Creates an extruded shape mesh.
  33009. * 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.
  33010. * Please consider using the same method from the MeshBuilder class instead.
  33011. *
  33012. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33013. * 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
  33014. * extruded along the Z axis.
  33015. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33016. * 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.
  33017. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33018. * 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
  33019. * 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
  33020. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33021. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33022. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33024. */
  33025. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33026. if (scene === void 0) { scene = null; }
  33027. var options = {
  33028. shape: shape,
  33029. path: path,
  33030. scale: scale,
  33031. rotation: rotation,
  33032. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33033. sideOrientation: sideOrientation,
  33034. instance: instance,
  33035. updatable: updatable
  33036. };
  33037. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33038. };
  33039. /**
  33040. * Creates an custom extruded shape mesh.
  33041. * 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.
  33042. * Please consider using the same method from the MeshBuilder class instead.
  33043. *
  33044. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33045. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  33046. * extruded along the Z axis.
  33047. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33048. * The parameter `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
  33049. * and the distance of this point from the begining of the path :
  33050. * ```javascript
  33051. * var rotationFunction = function(i, distance) {
  33052. * // do things
  33053. * return rotationValue; }
  33054. * ```
  33055. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33056. * 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
  33057. * and the distance of this point from the begining of the path :
  33058. * ```javascript
  33059. * var scaleFunction = function(i, distance) {
  33060. * // do things
  33061. * return scaleValue;}
  33062. * ```
  33063. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33064. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33065. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33066. * 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
  33067. * 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
  33068. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33069. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33072. */
  33073. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33074. var options = {
  33075. shape: shape,
  33076. path: path,
  33077. scaleFunction: scaleFunction,
  33078. rotationFunction: rotationFunction,
  33079. ribbonCloseArray: ribbonCloseArray,
  33080. ribbonClosePath: ribbonClosePath,
  33081. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33082. sideOrientation: sideOrientation,
  33083. instance: instance,
  33084. updatable: updatable
  33085. };
  33086. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33087. };
  33088. /**
  33089. * Creates lathe mesh.
  33090. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33091. * Please consider using the same method from the MeshBuilder class instead.
  33092. * 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
  33093. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33094. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33095. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33097. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33099. */
  33100. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33101. var options = {
  33102. shape: shape,
  33103. radius: radius,
  33104. tessellation: tessellation,
  33105. sideOrientation: sideOrientation,
  33106. updatable: updatable
  33107. };
  33108. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33109. };
  33110. /**
  33111. * Creates a plane mesh.
  33112. * Please consider using the same method from the MeshBuilder class instead.
  33113. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33117. */
  33118. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33119. var options = {
  33120. size: size,
  33121. width: size,
  33122. height: size,
  33123. sideOrientation: sideOrientation,
  33124. updatable: updatable
  33125. };
  33126. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33127. };
  33128. /**
  33129. * Creates a ground mesh.
  33130. * Please consider using the same method from the MeshBuilder class instead.
  33131. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33132. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33134. */
  33135. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33136. var options = {
  33137. width: width,
  33138. height: height,
  33139. subdivisions: subdivisions,
  33140. updatable: updatable
  33141. };
  33142. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33143. };
  33144. /**
  33145. * Creates a tiled ground mesh.
  33146. * Please consider using the same method from the MeshBuilder class instead.
  33147. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33148. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33149. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33150. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33151. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33152. * numbers of subdivisions on the ground width and height of each tile.
  33153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33154. */
  33155. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33156. var options = {
  33157. xmin: xmin,
  33158. zmin: zmin,
  33159. xmax: xmax,
  33160. zmax: zmax,
  33161. subdivisions: subdivisions,
  33162. precision: precision,
  33163. updatable: updatable
  33164. };
  33165. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33166. };
  33167. /**
  33168. * Creates a ground mesh from a height map.
  33169. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33170. * Please consider using the same method from the MeshBuilder class instead.
  33171. * The parameter `url` sets the URL of the height map image resource.
  33172. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33173. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33174. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33175. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33176. * 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).
  33177. * This function is passed the newly built mesh :
  33178. * ```javascript
  33179. * function(mesh) { // do things
  33180. * return; }
  33181. * ```
  33182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33183. */
  33184. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33185. var options = {
  33186. width: width,
  33187. height: height,
  33188. subdivisions: subdivisions,
  33189. minHeight: minHeight,
  33190. maxHeight: maxHeight,
  33191. updatable: updatable,
  33192. onReady: onReady
  33193. };
  33194. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33195. };
  33196. /**
  33197. * Creates a tube mesh.
  33198. * 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.
  33199. * Please consider using the same method from the MeshBuilder class instead.
  33200. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33201. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33202. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33203. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33204. * 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.
  33205. * It must return a radius value (positive float) :
  33206. * ```javascript
  33207. * var radiusFunction = function(i, distance) {
  33208. * // do things
  33209. * return radius; }
  33210. * ```
  33211. * 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
  33212. * 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
  33213. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33214. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33216. */
  33217. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33218. var options = {
  33219. path: path,
  33220. radius: radius,
  33221. tessellation: tessellation,
  33222. radiusFunction: radiusFunction,
  33223. arc: 1,
  33224. cap: cap,
  33225. updatable: updatable,
  33226. sideOrientation: sideOrientation,
  33227. instance: instance
  33228. };
  33229. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33230. };
  33231. /**
  33232. * Creates a polyhedron mesh.
  33233. * Please consider using the same method from the MeshBuilder class instead.
  33234. * 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
  33235. * to choose the wanted type.
  33236. * The parameter `size` (positive float, default 1) sets the polygon size.
  33237. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33238. * 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`.
  33239. * 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
  33240. * 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)`).
  33241. * 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
  33242. * 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.
  33243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33244. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33246. */
  33247. Mesh.CreatePolyhedron = function (name, options, scene) {
  33248. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33249. };
  33250. /**
  33251. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33252. * Please consider using the same method from the MeshBuilder class instead.
  33253. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33254. * 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`).
  33255. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33256. * 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.
  33257. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33258. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33259. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33260. */
  33261. Mesh.CreateIcoSphere = function (name, options, scene) {
  33262. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33263. };
  33264. /**
  33265. * Creates a decal mesh.
  33266. * Please consider using the same method from the MeshBuilder class instead.
  33267. * 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.
  33268. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33269. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33270. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33271. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33272. */
  33273. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33274. var options = {
  33275. position: position,
  33276. normal: normal,
  33277. size: size,
  33278. angle: angle
  33279. };
  33280. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33281. };
  33282. // Skeletons
  33283. /**
  33284. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33285. */
  33286. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33287. if (!this._sourcePositions) {
  33288. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33289. if (!source) {
  33290. return this._sourcePositions;
  33291. }
  33292. this._sourcePositions = new Float32Array(source);
  33293. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33294. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33295. }
  33296. }
  33297. return this._sourcePositions;
  33298. };
  33299. /**
  33300. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33301. */
  33302. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33303. if (!this._sourceNormals) {
  33304. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33305. if (!source) {
  33306. return this._sourceNormals;
  33307. }
  33308. this._sourceNormals = new Float32Array(source);
  33309. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33310. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33311. }
  33312. }
  33313. return this._sourceNormals;
  33314. };
  33315. /**
  33316. * Updates the vertex buffer by applying transformation from the bones.
  33317. * Returns the Mesh.
  33318. *
  33319. * @param {skeleton} skeleton to apply
  33320. */
  33321. Mesh.prototype.applySkeleton = function (skeleton) {
  33322. if (!this.geometry) {
  33323. return this;
  33324. }
  33325. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33326. return this;
  33327. }
  33328. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33329. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33330. return this;
  33331. }
  33332. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33333. return this;
  33334. }
  33335. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33336. return this;
  33337. }
  33338. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33339. return this;
  33340. }
  33341. if (!this._sourcePositions) {
  33342. var submeshes = this.subMeshes.slice();
  33343. this.setPositionsForCPUSkinning();
  33344. this.subMeshes = submeshes;
  33345. }
  33346. if (!this._sourceNormals) {
  33347. this.setNormalsForCPUSkinning();
  33348. }
  33349. // positionsData checks for not being Float32Array will only pass at most once
  33350. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33351. if (!positionsData) {
  33352. return this;
  33353. }
  33354. if (!(positionsData instanceof Float32Array)) {
  33355. positionsData = new Float32Array(positionsData);
  33356. }
  33357. // normalsData checks for not being Float32Array will only pass at most once
  33358. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33359. if (!normalsData) {
  33360. return this;
  33361. }
  33362. if (!(normalsData instanceof Float32Array)) {
  33363. normalsData = new Float32Array(normalsData);
  33364. }
  33365. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33366. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33367. if (!matricesWeightsData || !matricesIndicesData) {
  33368. return this;
  33369. }
  33370. var needExtras = this.numBoneInfluencers > 4;
  33371. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33372. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33373. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33374. var tempVector3 = BABYLON.Vector3.Zero();
  33375. var finalMatrix = new BABYLON.Matrix();
  33376. var tempMatrix = new BABYLON.Matrix();
  33377. var matWeightIdx = 0;
  33378. var inf;
  33379. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33380. var weight;
  33381. for (inf = 0; inf < 4; inf++) {
  33382. weight = matricesWeightsData[matWeightIdx + inf];
  33383. if (weight > 0) {
  33384. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33385. finalMatrix.addToSelf(tempMatrix);
  33386. }
  33387. else
  33388. break;
  33389. }
  33390. if (needExtras) {
  33391. for (inf = 0; inf < 4; inf++) {
  33392. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33393. if (weight > 0) {
  33394. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33395. finalMatrix.addToSelf(tempMatrix);
  33396. }
  33397. else
  33398. break;
  33399. }
  33400. }
  33401. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33402. tempVector3.toArray(positionsData, index);
  33403. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33404. tempVector3.toArray(normalsData, index);
  33405. finalMatrix.reset();
  33406. }
  33407. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33408. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33409. return this;
  33410. };
  33411. // Tools
  33412. /**
  33413. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33414. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33415. */
  33416. Mesh.MinMax = function (meshes) {
  33417. var minVector = null;
  33418. var maxVector = null;
  33419. meshes.forEach(function (mesh, index, array) {
  33420. var boundingInfo = mesh.getBoundingInfo();
  33421. var boundingBox = boundingInfo.boundingBox;
  33422. if (!minVector || !maxVector) {
  33423. minVector = boundingBox.minimumWorld;
  33424. maxVector = boundingBox.maximumWorld;
  33425. }
  33426. else {
  33427. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33428. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33429. }
  33430. });
  33431. if (!minVector || !maxVector) {
  33432. return {
  33433. min: BABYLON.Vector3.Zero(),
  33434. max: BABYLON.Vector3.Zero()
  33435. };
  33436. }
  33437. return {
  33438. min: minVector,
  33439. max: maxVector
  33440. };
  33441. };
  33442. /**
  33443. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33444. */
  33445. Mesh.Center = function (meshesOrMinMaxVector) {
  33446. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33447. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33448. };
  33449. /**
  33450. * Merge the array of meshes into a single mesh for performance reasons.
  33451. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33452. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33453. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33454. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33455. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33456. */
  33457. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33458. if (disposeSource === void 0) { disposeSource = true; }
  33459. var index;
  33460. if (!allow32BitsIndices) {
  33461. var totalVertices = 0;
  33462. // Counting vertices
  33463. for (index = 0; index < meshes.length; index++) {
  33464. if (meshes[index]) {
  33465. totalVertices += meshes[index].getTotalVertices();
  33466. if (totalVertices > 65536) {
  33467. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33468. return null;
  33469. }
  33470. }
  33471. }
  33472. }
  33473. // Merge
  33474. var vertexData = null;
  33475. var otherVertexData;
  33476. var indiceArray = new Array();
  33477. var source = null;
  33478. for (index = 0; index < meshes.length; index++) {
  33479. if (meshes[index]) {
  33480. meshes[index].computeWorldMatrix(true);
  33481. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33482. otherVertexData.transform(meshes[index].getWorldMatrix());
  33483. if (vertexData) {
  33484. vertexData.merge(otherVertexData);
  33485. }
  33486. else {
  33487. vertexData = otherVertexData;
  33488. source = meshes[index];
  33489. }
  33490. if (subdivideWithSubMeshes) {
  33491. indiceArray.push(meshes[index].getTotalIndices());
  33492. }
  33493. }
  33494. }
  33495. source = source;
  33496. if (!meshSubclass) {
  33497. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33498. }
  33499. vertexData.applyToMesh(meshSubclass);
  33500. // Setting properties
  33501. meshSubclass.material = source.material;
  33502. meshSubclass.checkCollisions = source.checkCollisions;
  33503. // Cleaning
  33504. if (disposeSource) {
  33505. for (index = 0; index < meshes.length; index++) {
  33506. if (meshes[index]) {
  33507. meshes[index].dispose();
  33508. }
  33509. }
  33510. }
  33511. // Subdivide
  33512. if (subdivideWithSubMeshes) {
  33513. //-- Suppresions du submesh global
  33514. meshSubclass.releaseSubMeshes();
  33515. index = 0;
  33516. var offset = 0;
  33517. //-- aplique la subdivision en fonction du tableau d'indices
  33518. while (index < indiceArray.length) {
  33519. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33520. offset += indiceArray[index];
  33521. index++;
  33522. }
  33523. }
  33524. return meshSubclass;
  33525. };
  33526. // Consts
  33527. Mesh._FRONTSIDE = 0;
  33528. Mesh._BACKSIDE = 1;
  33529. Mesh._DOUBLESIDE = 2;
  33530. Mesh._DEFAULTSIDE = 0;
  33531. Mesh._NO_CAP = 0;
  33532. Mesh._CAP_START = 1;
  33533. Mesh._CAP_END = 2;
  33534. Mesh._CAP_ALL = 3;
  33535. return Mesh;
  33536. }(BABYLON.AbstractMesh));
  33537. BABYLON.Mesh = Mesh;
  33538. })(BABYLON || (BABYLON = {}));
  33539. //# sourceMappingURL=babylon.mesh.js.map
  33540. "use strict";
  33541. var BABYLON;
  33542. (function (BABYLON) {
  33543. var BaseSubMesh = /** @class */ (function () {
  33544. function BaseSubMesh() {
  33545. }
  33546. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33547. get: function () {
  33548. return this._materialEffect;
  33549. },
  33550. enumerable: true,
  33551. configurable: true
  33552. });
  33553. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33554. if (defines === void 0) { defines = null; }
  33555. if (this._materialEffect === effect) {
  33556. if (!effect) {
  33557. this._materialDefines = null;
  33558. }
  33559. return;
  33560. }
  33561. this._materialDefines = defines;
  33562. this._materialEffect = effect;
  33563. };
  33564. return BaseSubMesh;
  33565. }());
  33566. BABYLON.BaseSubMesh = BaseSubMesh;
  33567. var SubMesh = /** @class */ (function (_super) {
  33568. __extends(SubMesh, _super);
  33569. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33570. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33571. var _this = _super.call(this) || this;
  33572. _this.materialIndex = materialIndex;
  33573. _this.verticesStart = verticesStart;
  33574. _this.verticesCount = verticesCount;
  33575. _this.indexStart = indexStart;
  33576. _this.indexCount = indexCount;
  33577. _this._renderId = 0;
  33578. _this._mesh = mesh;
  33579. _this._renderingMesh = renderingMesh || mesh;
  33580. mesh.subMeshes.push(_this);
  33581. _this._trianglePlanes = [];
  33582. _this._id = mesh.subMeshes.length - 1;
  33583. if (createBoundingBox) {
  33584. _this.refreshBoundingInfo();
  33585. mesh.computeWorldMatrix(true);
  33586. }
  33587. return _this;
  33588. }
  33589. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33590. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33591. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33592. };
  33593. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33594. get: function () {
  33595. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33596. },
  33597. enumerable: true,
  33598. configurable: true
  33599. });
  33600. /**
  33601. * Returns the submesh BoudingInfo object.
  33602. */
  33603. SubMesh.prototype.getBoundingInfo = function () {
  33604. if (this.IsGlobal) {
  33605. return this._mesh.getBoundingInfo();
  33606. }
  33607. return this._boundingInfo;
  33608. };
  33609. /**
  33610. * Sets the submesh BoundingInfo.
  33611. * Return the SubMesh.
  33612. */
  33613. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33614. this._boundingInfo = boundingInfo;
  33615. return this;
  33616. };
  33617. /**
  33618. * Returns the mesh of the current submesh.
  33619. */
  33620. SubMesh.prototype.getMesh = function () {
  33621. return this._mesh;
  33622. };
  33623. /**
  33624. * Returns the rendering mesh of the submesh.
  33625. */
  33626. SubMesh.prototype.getRenderingMesh = function () {
  33627. return this._renderingMesh;
  33628. };
  33629. /**
  33630. * Returns the submesh material.
  33631. */
  33632. SubMesh.prototype.getMaterial = function () {
  33633. var rootMaterial = this._renderingMesh.material;
  33634. if (rootMaterial === null || rootMaterial === undefined) {
  33635. return this._mesh.getScene().defaultMaterial;
  33636. }
  33637. else if (rootMaterial.getSubMaterial) {
  33638. var multiMaterial = rootMaterial;
  33639. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33640. if (this._currentMaterial !== effectiveMaterial) {
  33641. this._currentMaterial = effectiveMaterial;
  33642. this._materialDefines = null;
  33643. }
  33644. return effectiveMaterial;
  33645. }
  33646. return rootMaterial;
  33647. };
  33648. // Methods
  33649. /**
  33650. * Sets a new updated BoundingInfo object to the submesh.
  33651. * Returns the SubMesh.
  33652. */
  33653. SubMesh.prototype.refreshBoundingInfo = function () {
  33654. this._lastColliderWorldVertices = null;
  33655. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33656. return this;
  33657. }
  33658. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33659. if (!data) {
  33660. this._boundingInfo = this._mesh.getBoundingInfo();
  33661. return this;
  33662. }
  33663. var indices = this._renderingMesh.getIndices();
  33664. var extend;
  33665. //is this the only submesh?
  33666. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33667. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33668. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33669. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33670. }
  33671. else {
  33672. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33673. }
  33674. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33675. return this;
  33676. };
  33677. SubMesh.prototype._checkCollision = function (collider) {
  33678. var boundingInfo = this.getBoundingInfo();
  33679. return boundingInfo._checkCollision(collider);
  33680. };
  33681. /**
  33682. * Updates the submesh BoundingInfo.
  33683. * Returns the Submesh.
  33684. */
  33685. SubMesh.prototype.updateBoundingInfo = function (world) {
  33686. var boundingInfo = this.getBoundingInfo();
  33687. if (!boundingInfo) {
  33688. this.refreshBoundingInfo();
  33689. boundingInfo = this.getBoundingInfo();
  33690. }
  33691. boundingInfo.update(world);
  33692. return this;
  33693. };
  33694. /**
  33695. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33696. * Boolean returned.
  33697. */
  33698. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33699. var boundingInfo = this.getBoundingInfo();
  33700. if (!boundingInfo) {
  33701. return false;
  33702. }
  33703. return boundingInfo.isInFrustum(frustumPlanes);
  33704. };
  33705. /**
  33706. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33707. * Boolean returned.
  33708. */
  33709. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33710. var boundingInfo = this.getBoundingInfo();
  33711. if (!boundingInfo) {
  33712. return false;
  33713. }
  33714. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33715. };
  33716. /**
  33717. * Renders the submesh.
  33718. * Returns it.
  33719. */
  33720. SubMesh.prototype.render = function (enableAlphaMode) {
  33721. this._renderingMesh.render(this, enableAlphaMode);
  33722. return this;
  33723. };
  33724. /**
  33725. * Returns a new Index Buffer.
  33726. * Type returned : WebGLBuffer.
  33727. */
  33728. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33729. if (!this._linesIndexBuffer) {
  33730. var linesIndices = [];
  33731. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33732. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33733. }
  33734. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33735. this.linesIndexCount = linesIndices.length;
  33736. }
  33737. return this._linesIndexBuffer;
  33738. };
  33739. /**
  33740. * True is the passed Ray intersects the submesh bounding box.
  33741. * Boolean returned.
  33742. */
  33743. SubMesh.prototype.canIntersects = function (ray) {
  33744. var boundingInfo = this.getBoundingInfo();
  33745. if (!boundingInfo) {
  33746. return false;
  33747. }
  33748. return ray.intersectsBox(boundingInfo.boundingBox);
  33749. };
  33750. /**
  33751. * Returns an object IntersectionInfo.
  33752. */
  33753. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33754. var intersectInfo = null;
  33755. var material = this.getMaterial();
  33756. if (!material) {
  33757. return null;
  33758. }
  33759. switch (material.fillMode) {
  33760. case BABYLON.Material.PointListDrawMode:
  33761. case BABYLON.Material.LineListDrawMode:
  33762. case BABYLON.Material.LineLoopDrawMode:
  33763. case BABYLON.Material.LineStripDrawMode:
  33764. case BABYLON.Material.TriangleFanDrawMode:
  33765. case BABYLON.Material.TriangleStripDrawMode:
  33766. return null;
  33767. }
  33768. // LineMesh first as it's also a Mesh...
  33769. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33770. var lineMesh = this._mesh;
  33771. // Line test
  33772. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33773. var p0 = positions[indices[index]];
  33774. var p1 = positions[indices[index + 1]];
  33775. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33776. if (length < 0) {
  33777. continue;
  33778. }
  33779. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33780. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33781. if (fastCheck) {
  33782. break;
  33783. }
  33784. }
  33785. }
  33786. }
  33787. else {
  33788. // Triangles test
  33789. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33790. var p0 = positions[indices[index]];
  33791. var p1 = positions[indices[index + 1]];
  33792. var p2 = positions[indices[index + 2]];
  33793. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33794. if (currentIntersectInfo) {
  33795. if (currentIntersectInfo.distance < 0) {
  33796. continue;
  33797. }
  33798. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33799. intersectInfo = currentIntersectInfo;
  33800. intersectInfo.faceId = index / 3;
  33801. if (fastCheck) {
  33802. break;
  33803. }
  33804. }
  33805. }
  33806. }
  33807. }
  33808. return intersectInfo;
  33809. };
  33810. SubMesh.prototype._rebuild = function () {
  33811. if (this._linesIndexBuffer) {
  33812. this._linesIndexBuffer = null;
  33813. }
  33814. };
  33815. // Clone
  33816. /**
  33817. * Creates a new Submesh from the passed Mesh.
  33818. */
  33819. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33820. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33821. if (!this.IsGlobal) {
  33822. var boundingInfo = this.getBoundingInfo();
  33823. if (!boundingInfo) {
  33824. return result;
  33825. }
  33826. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33827. }
  33828. return result;
  33829. };
  33830. // Dispose
  33831. /**
  33832. * Disposes the Submesh.
  33833. * Returns nothing.
  33834. */
  33835. SubMesh.prototype.dispose = function () {
  33836. if (this._linesIndexBuffer) {
  33837. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33838. this._linesIndexBuffer = null;
  33839. }
  33840. // Remove from mesh
  33841. var index = this._mesh.subMeshes.indexOf(this);
  33842. this._mesh.subMeshes.splice(index, 1);
  33843. };
  33844. // Statics
  33845. /**
  33846. * Creates a new Submesh from the passed parameters :
  33847. * - materialIndex (integer) : the index of the main mesh material.
  33848. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33849. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33850. * - mesh (Mesh) : the main mesh to create the submesh from.
  33851. * - renderingMesh (optional Mesh) : rendering mesh.
  33852. */
  33853. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33854. var minVertexIndex = Number.MAX_VALUE;
  33855. var maxVertexIndex = -Number.MAX_VALUE;
  33856. renderingMesh = (renderingMesh || mesh);
  33857. var indices = renderingMesh.getIndices();
  33858. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33859. var vertexIndex = indices[index];
  33860. if (vertexIndex < minVertexIndex)
  33861. minVertexIndex = vertexIndex;
  33862. if (vertexIndex > maxVertexIndex)
  33863. maxVertexIndex = vertexIndex;
  33864. }
  33865. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33866. };
  33867. return SubMesh;
  33868. }(BaseSubMesh));
  33869. BABYLON.SubMesh = SubMesh;
  33870. })(BABYLON || (BABYLON = {}));
  33871. //# sourceMappingURL=babylon.subMesh.js.map
  33872. "use strict";
  33873. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33874. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33875. s = arguments[i];
  33876. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33877. t[p] = s[p];
  33878. }
  33879. return t;
  33880. };
  33881. var BABYLON;
  33882. (function (BABYLON) {
  33883. /**
  33884. * Manages the defines for the Material
  33885. */
  33886. var MaterialDefines = /** @class */ (function () {
  33887. function MaterialDefines() {
  33888. this._isDirty = true;
  33889. /** @ignore */
  33890. this._areLightsDirty = true;
  33891. /** @ignore */
  33892. this._areAttributesDirty = true;
  33893. /** @ignore */
  33894. this._areTexturesDirty = true;
  33895. /** @ignore */
  33896. this._areFresnelDirty = true;
  33897. /** @ignore */
  33898. this._areMiscDirty = true;
  33899. /** @ignore */
  33900. this._areImageProcessingDirty = true;
  33901. /** @ignore */
  33902. this._normals = false;
  33903. /** @ignore */
  33904. this._uvs = false;
  33905. /** @ignore */
  33906. this._needNormals = false;
  33907. /** @ignore */
  33908. this._needUVs = false;
  33909. }
  33910. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33911. /**
  33912. * Specifies if the material needs to be re-calculated
  33913. */
  33914. get: function () {
  33915. return this._isDirty;
  33916. },
  33917. enumerable: true,
  33918. configurable: true
  33919. });
  33920. /**
  33921. * Marks the material to indicate that it has been re-calculated
  33922. */
  33923. MaterialDefines.prototype.markAsProcessed = function () {
  33924. this._isDirty = false;
  33925. this._areAttributesDirty = false;
  33926. this._areTexturesDirty = false;
  33927. this._areFresnelDirty = false;
  33928. this._areLightsDirty = false;
  33929. this._areMiscDirty = false;
  33930. this._areImageProcessingDirty = false;
  33931. };
  33932. /**
  33933. * Marks the material to indicate that it needs to be re-calculated
  33934. */
  33935. MaterialDefines.prototype.markAsUnprocessed = function () {
  33936. this._isDirty = true;
  33937. };
  33938. /**
  33939. * Marks the material to indicate all of its defines need to be re-calculated
  33940. */
  33941. MaterialDefines.prototype.markAllAsDirty = function () {
  33942. this._areTexturesDirty = true;
  33943. this._areAttributesDirty = true;
  33944. this._areLightsDirty = true;
  33945. this._areFresnelDirty = true;
  33946. this._areMiscDirty = true;
  33947. this._areImageProcessingDirty = true;
  33948. this._isDirty = true;
  33949. };
  33950. /**
  33951. * Marks the material to indicate that image processing needs to be re-calculated
  33952. */
  33953. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33954. this._areImageProcessingDirty = true;
  33955. this._isDirty = true;
  33956. };
  33957. /**
  33958. * Marks the material to indicate the lights need to be re-calculated
  33959. */
  33960. MaterialDefines.prototype.markAsLightDirty = function () {
  33961. this._areLightsDirty = true;
  33962. this._isDirty = true;
  33963. };
  33964. /**
  33965. * Marks the attribute state as changed
  33966. */
  33967. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33968. this._areAttributesDirty = true;
  33969. this._isDirty = true;
  33970. };
  33971. /**
  33972. * Marks the texture state as changed
  33973. */
  33974. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33975. this._areTexturesDirty = true;
  33976. this._isDirty = true;
  33977. };
  33978. /**
  33979. * Marks the fresnel state as changed
  33980. */
  33981. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33982. this._areFresnelDirty = true;
  33983. this._isDirty = true;
  33984. };
  33985. /**
  33986. * Marks the misc state as changed
  33987. */
  33988. MaterialDefines.prototype.markAsMiscDirty = function () {
  33989. this._areMiscDirty = true;
  33990. this._isDirty = true;
  33991. };
  33992. /**
  33993. * Rebuilds the material defines
  33994. */
  33995. MaterialDefines.prototype.rebuild = function () {
  33996. if (this._keys) {
  33997. delete this._keys;
  33998. }
  33999. this._keys = [];
  34000. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34001. var key = _a[_i];
  34002. if (key[0] === "_") {
  34003. continue;
  34004. }
  34005. this._keys.push(key);
  34006. }
  34007. };
  34008. /**
  34009. * Specifies if two material defines are equal
  34010. * @param other - A material define instance to compare to
  34011. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34012. */
  34013. MaterialDefines.prototype.isEqual = function (other) {
  34014. if (this._keys.length !== other._keys.length) {
  34015. return false;
  34016. }
  34017. for (var index = 0; index < this._keys.length; index++) {
  34018. var prop = this._keys[index];
  34019. if (this[prop] !== other[prop]) {
  34020. return false;
  34021. }
  34022. }
  34023. return true;
  34024. };
  34025. /**
  34026. * Clones this instance's defines to another instance
  34027. * @param other - material defines to clone values to
  34028. */
  34029. MaterialDefines.prototype.cloneTo = function (other) {
  34030. if (this._keys.length !== other._keys.length) {
  34031. other._keys = this._keys.slice(0);
  34032. }
  34033. for (var index = 0; index < this._keys.length; index++) {
  34034. var prop = this._keys[index];
  34035. other[prop] = this[prop];
  34036. }
  34037. };
  34038. /**
  34039. * Resets the material define values
  34040. */
  34041. MaterialDefines.prototype.reset = function () {
  34042. for (var index = 0; index < this._keys.length; index++) {
  34043. var prop = this._keys[index];
  34044. var type = typeof this[prop];
  34045. switch (type) {
  34046. case "number":
  34047. this[prop] = 0;
  34048. break;
  34049. case "string":
  34050. this[prop] = "";
  34051. break;
  34052. default:
  34053. this[prop] = false;
  34054. break;
  34055. }
  34056. }
  34057. };
  34058. /**
  34059. * Converts the material define values to a string
  34060. * @returns - String of material define information
  34061. */
  34062. MaterialDefines.prototype.toString = function () {
  34063. var result = "";
  34064. for (var index = 0; index < this._keys.length; index++) {
  34065. var prop = this._keys[index];
  34066. var value = this[prop];
  34067. var type = typeof value;
  34068. switch (type) {
  34069. case "number":
  34070. case "string":
  34071. result += "#define " + prop + " " + value + "\n";
  34072. break;
  34073. default:
  34074. if (value) {
  34075. result += "#define " + prop + "\n";
  34076. }
  34077. break;
  34078. }
  34079. }
  34080. return result;
  34081. };
  34082. return MaterialDefines;
  34083. }());
  34084. BABYLON.MaterialDefines = MaterialDefines;
  34085. /**
  34086. * Base class for the main features of a material in Babylon.js
  34087. */
  34088. var Material = /** @class */ (function () {
  34089. /**
  34090. * Creates a material instance
  34091. * @param name defines the name of the material
  34092. * @param scene defines the scene to reference
  34093. * @param doNotAdd specifies if the material should be added to the scene
  34094. */
  34095. function Material(name, scene, doNotAdd) {
  34096. /**
  34097. * Specifies if the ready state should be checked on each call
  34098. */
  34099. this.checkReadyOnEveryCall = false;
  34100. /**
  34101. * Specifies if the ready state should be checked once
  34102. */
  34103. this.checkReadyOnlyOnce = false;
  34104. /**
  34105. * The state of the material
  34106. */
  34107. this.state = "";
  34108. /**
  34109. * The alpha value of the material
  34110. */
  34111. this._alpha = 1.0;
  34112. /**
  34113. * Specifies if back face culling is enabled
  34114. */
  34115. this._backFaceCulling = true;
  34116. /**
  34117. * Specifies if the material should be serialized
  34118. */
  34119. this.doNotSerialize = false;
  34120. /**
  34121. * Specifies if the effect should be stored on sub meshes
  34122. */
  34123. this.storeEffectOnSubMeshes = false;
  34124. /**
  34125. * An event triggered when the material is disposed
  34126. */
  34127. this.onDisposeObservable = new BABYLON.Observable();
  34128. /**
  34129. * An event triggered when the material is bound
  34130. */
  34131. this.onBindObservable = new BABYLON.Observable();
  34132. /**
  34133. * An event triggered when the material is unbound
  34134. */
  34135. this.onUnBindObservable = new BABYLON.Observable();
  34136. /**
  34137. * Stores the value of the alpha mode
  34138. */
  34139. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34140. /**
  34141. * Stores the state of the need depth pre-pass value
  34142. */
  34143. this._needDepthPrePass = false;
  34144. /**
  34145. * Specifies if depth writing should be disabled
  34146. */
  34147. this.disableDepthWrite = false;
  34148. /**
  34149. * Specifies if depth writing should be forced
  34150. */
  34151. this.forceDepthWrite = false;
  34152. /**
  34153. * Specifies if there should be a separate pass for culling
  34154. */
  34155. this.separateCullingPass = false;
  34156. /**
  34157. * Stores the state specifing if fog should be enabled
  34158. */
  34159. this._fogEnabled = true;
  34160. /**
  34161. * Stores the size of points
  34162. */
  34163. this.pointSize = 1.0;
  34164. /**
  34165. * Stores the z offset value
  34166. */
  34167. this.zOffset = 0;
  34168. /**
  34169. * Specifies if the material was previously ready
  34170. */
  34171. this._wasPreviouslyReady = false;
  34172. /**
  34173. * Stores the fill mode state
  34174. */
  34175. this._fillMode = Material.TriangleFillMode;
  34176. this.name = name;
  34177. this.id = name || BABYLON.Tools.RandomId();
  34178. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34179. if (this._scene.useRightHandedSystem) {
  34180. this.sideOrientation = Material.ClockWiseSideOrientation;
  34181. }
  34182. else {
  34183. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34184. }
  34185. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34186. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34187. if (!doNotAdd) {
  34188. this._scene.materials.push(this);
  34189. }
  34190. }
  34191. Object.defineProperty(Material, "TriangleFillMode", {
  34192. /**
  34193. * Returns the triangle fill mode
  34194. */
  34195. get: function () {
  34196. return Material._TriangleFillMode;
  34197. },
  34198. enumerable: true,
  34199. configurable: true
  34200. });
  34201. Object.defineProperty(Material, "WireFrameFillMode", {
  34202. /**
  34203. * Returns the wireframe mode
  34204. */
  34205. get: function () {
  34206. return Material._WireFrameFillMode;
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. Object.defineProperty(Material, "PointFillMode", {
  34212. /**
  34213. * Returns the point fill mode
  34214. */
  34215. get: function () {
  34216. return Material._PointFillMode;
  34217. },
  34218. enumerable: true,
  34219. configurable: true
  34220. });
  34221. Object.defineProperty(Material, "PointListDrawMode", {
  34222. /**
  34223. * Returns the point list draw mode
  34224. */
  34225. get: function () {
  34226. return Material._PointListDrawMode;
  34227. },
  34228. enumerable: true,
  34229. configurable: true
  34230. });
  34231. Object.defineProperty(Material, "LineListDrawMode", {
  34232. /**
  34233. * Returns the line list draw mode
  34234. */
  34235. get: function () {
  34236. return Material._LineListDrawMode;
  34237. },
  34238. enumerable: true,
  34239. configurable: true
  34240. });
  34241. Object.defineProperty(Material, "LineLoopDrawMode", {
  34242. /**
  34243. * Returns the line loop draw mode
  34244. */
  34245. get: function () {
  34246. return Material._LineLoopDrawMode;
  34247. },
  34248. enumerable: true,
  34249. configurable: true
  34250. });
  34251. Object.defineProperty(Material, "LineStripDrawMode", {
  34252. /**
  34253. * Returns the line strip draw mode
  34254. */
  34255. get: function () {
  34256. return Material._LineStripDrawMode;
  34257. },
  34258. enumerable: true,
  34259. configurable: true
  34260. });
  34261. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34262. /**
  34263. * Returns the triangle strip draw mode
  34264. */
  34265. get: function () {
  34266. return Material._TriangleStripDrawMode;
  34267. },
  34268. enumerable: true,
  34269. configurable: true
  34270. });
  34271. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34272. /**
  34273. * Returns the triangle fan draw mode
  34274. */
  34275. get: function () {
  34276. return Material._TriangleFanDrawMode;
  34277. },
  34278. enumerable: true,
  34279. configurable: true
  34280. });
  34281. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34282. /**
  34283. * Returns the clock-wise side orientation
  34284. */
  34285. get: function () {
  34286. return Material._ClockWiseSideOrientation;
  34287. },
  34288. enumerable: true,
  34289. configurable: true
  34290. });
  34291. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34292. /**
  34293. * Returns the counter clock-wise side orientation
  34294. */
  34295. get: function () {
  34296. return Material._CounterClockWiseSideOrientation;
  34297. },
  34298. enumerable: true,
  34299. configurable: true
  34300. });
  34301. Object.defineProperty(Material, "TextureDirtyFlag", {
  34302. /**
  34303. * Returns the dirty texture flag value
  34304. */
  34305. get: function () {
  34306. return Material._TextureDirtyFlag;
  34307. },
  34308. enumerable: true,
  34309. configurable: true
  34310. });
  34311. Object.defineProperty(Material, "LightDirtyFlag", {
  34312. /**
  34313. * Returns the dirty light flag value
  34314. */
  34315. get: function () {
  34316. return Material._LightDirtyFlag;
  34317. },
  34318. enumerable: true,
  34319. configurable: true
  34320. });
  34321. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34322. /**
  34323. * Returns the dirty fresnel flag value
  34324. */
  34325. get: function () {
  34326. return Material._FresnelDirtyFlag;
  34327. },
  34328. enumerable: true,
  34329. configurable: true
  34330. });
  34331. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34332. /**
  34333. * Returns the dirty attributes flag value
  34334. */
  34335. get: function () {
  34336. return Material._AttributesDirtyFlag;
  34337. },
  34338. enumerable: true,
  34339. configurable: true
  34340. });
  34341. Object.defineProperty(Material, "MiscDirtyFlag", {
  34342. /**
  34343. * Returns the dirty misc flag value
  34344. */
  34345. get: function () {
  34346. return Material._MiscDirtyFlag;
  34347. },
  34348. enumerable: true,
  34349. configurable: true
  34350. });
  34351. Object.defineProperty(Material.prototype, "alpha", {
  34352. /**
  34353. * Gets the alpha value of the material
  34354. */
  34355. get: function () {
  34356. return this._alpha;
  34357. },
  34358. /**
  34359. * Sets the alpha value of the material
  34360. */
  34361. set: function (value) {
  34362. if (this._alpha === value) {
  34363. return;
  34364. }
  34365. this._alpha = value;
  34366. this.markAsDirty(Material.MiscDirtyFlag);
  34367. },
  34368. enumerable: true,
  34369. configurable: true
  34370. });
  34371. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34372. /**
  34373. * Gets the back-face culling state
  34374. */
  34375. get: function () {
  34376. return this._backFaceCulling;
  34377. },
  34378. /**
  34379. * Sets the back-face culling state
  34380. */
  34381. set: function (value) {
  34382. if (this._backFaceCulling === value) {
  34383. return;
  34384. }
  34385. this._backFaceCulling = value;
  34386. this.markAsDirty(Material.TextureDirtyFlag);
  34387. },
  34388. enumerable: true,
  34389. configurable: true
  34390. });
  34391. Object.defineProperty(Material.prototype, "onDispose", {
  34392. /**
  34393. * Called during a dispose event
  34394. */
  34395. set: function (callback) {
  34396. if (this._onDisposeObserver) {
  34397. this.onDisposeObservable.remove(this._onDisposeObserver);
  34398. }
  34399. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34400. },
  34401. enumerable: true,
  34402. configurable: true
  34403. });
  34404. Object.defineProperty(Material.prototype, "onBind", {
  34405. /**
  34406. * Called during a bind event
  34407. */
  34408. set: function (callback) {
  34409. if (this._onBindObserver) {
  34410. this.onBindObservable.remove(this._onBindObserver);
  34411. }
  34412. this._onBindObserver = this.onBindObservable.add(callback);
  34413. },
  34414. enumerable: true,
  34415. configurable: true
  34416. });
  34417. Object.defineProperty(Material.prototype, "alphaMode", {
  34418. /**
  34419. * Gets the value of the alpha mode
  34420. */
  34421. get: function () {
  34422. return this._alphaMode;
  34423. },
  34424. /**
  34425. * Sets the value of the alpha mode.
  34426. *
  34427. * | Value | Type | Description |
  34428. * | --- | --- | --- |
  34429. * | 0 | ALPHA_DISABLE | |
  34430. * | 1 | ALPHA_ADD | |
  34431. * | 2 | ALPHA_COMBINE | |
  34432. * | 3 | ALPHA_SUBTRACT | |
  34433. * | 4 | ALPHA_MULTIPLY | |
  34434. * | 5 | ALPHA_MAXIMIZED | |
  34435. * | 6 | ALPHA_ONEONE | |
  34436. * | 7 | ALPHA_PREMULTIPLIED | |
  34437. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34438. * | 9 | ALPHA_INTERPOLATE | |
  34439. * | 10 | ALPHA_SCREENMODE | |
  34440. *
  34441. */
  34442. set: function (value) {
  34443. if (this._alphaMode === value) {
  34444. return;
  34445. }
  34446. this._alphaMode = value;
  34447. this.markAsDirty(Material.TextureDirtyFlag);
  34448. },
  34449. enumerable: true,
  34450. configurable: true
  34451. });
  34452. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34453. /**
  34454. * Gets the depth pre-pass value
  34455. */
  34456. get: function () {
  34457. return this._needDepthPrePass;
  34458. },
  34459. /**
  34460. * Sets the need depth pre-pass value
  34461. */
  34462. set: function (value) {
  34463. if (this._needDepthPrePass === value) {
  34464. return;
  34465. }
  34466. this._needDepthPrePass = value;
  34467. if (this._needDepthPrePass) {
  34468. this.checkReadyOnEveryCall = true;
  34469. }
  34470. },
  34471. enumerable: true,
  34472. configurable: true
  34473. });
  34474. Object.defineProperty(Material.prototype, "fogEnabled", {
  34475. /**
  34476. * Gets the value of the fog enabled state
  34477. */
  34478. get: function () {
  34479. return this._fogEnabled;
  34480. },
  34481. /**
  34482. * Sets the state for enabling fog
  34483. */
  34484. set: function (value) {
  34485. if (this._fogEnabled === value) {
  34486. return;
  34487. }
  34488. this._fogEnabled = value;
  34489. this.markAsDirty(Material.MiscDirtyFlag);
  34490. },
  34491. enumerable: true,
  34492. configurable: true
  34493. });
  34494. Object.defineProperty(Material.prototype, "wireframe", {
  34495. /**
  34496. * Gets a value specifying if wireframe mode is enabled
  34497. */
  34498. get: function () {
  34499. switch (this._fillMode) {
  34500. case Material.WireFrameFillMode:
  34501. case Material.LineListDrawMode:
  34502. case Material.LineLoopDrawMode:
  34503. case Material.LineStripDrawMode:
  34504. return true;
  34505. }
  34506. return this._scene.forceWireframe;
  34507. },
  34508. /**
  34509. * Sets the state of wireframe mode
  34510. */
  34511. set: function (value) {
  34512. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34513. },
  34514. enumerable: true,
  34515. configurable: true
  34516. });
  34517. Object.defineProperty(Material.prototype, "pointsCloud", {
  34518. /**
  34519. * Gets the value specifying if point clouds are enabled
  34520. */
  34521. get: function () {
  34522. switch (this._fillMode) {
  34523. case Material.PointFillMode:
  34524. case Material.PointListDrawMode:
  34525. return true;
  34526. }
  34527. return this._scene.forcePointsCloud;
  34528. },
  34529. /**
  34530. * Sets the state of point cloud mode
  34531. */
  34532. set: function (value) {
  34533. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. Object.defineProperty(Material.prototype, "fillMode", {
  34539. /**
  34540. * Gets the material fill mode
  34541. */
  34542. get: function () {
  34543. return this._fillMode;
  34544. },
  34545. /**
  34546. * Sets the material fill mode
  34547. */
  34548. set: function (value) {
  34549. if (this._fillMode === value) {
  34550. return;
  34551. }
  34552. this._fillMode = value;
  34553. this.markAsDirty(Material.MiscDirtyFlag);
  34554. },
  34555. enumerable: true,
  34556. configurable: true
  34557. });
  34558. /**
  34559. * Returns a string representation of the current material
  34560. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34561. * @returns a string with material information
  34562. */
  34563. Material.prototype.toString = function (fullDetails) {
  34564. var ret = "Name: " + this.name;
  34565. if (fullDetails) {
  34566. }
  34567. return ret;
  34568. };
  34569. /**
  34570. * Gets the class name of the material
  34571. * @returns a string with the class name of the material
  34572. */
  34573. Material.prototype.getClassName = function () {
  34574. return "Material";
  34575. };
  34576. Object.defineProperty(Material.prototype, "isFrozen", {
  34577. /**
  34578. * Specifies if updates for the material been locked
  34579. */
  34580. get: function () {
  34581. return this.checkReadyOnlyOnce;
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. /**
  34587. * Locks updates for the material
  34588. */
  34589. Material.prototype.freeze = function () {
  34590. this.checkReadyOnlyOnce = true;
  34591. };
  34592. /**
  34593. * Unlocks updates for the material
  34594. */
  34595. Material.prototype.unfreeze = function () {
  34596. this.checkReadyOnlyOnce = false;
  34597. };
  34598. /**
  34599. * Specifies if the material is ready to be used
  34600. * @param mesh defines the mesh to check
  34601. * @param useInstances specifies if instances should be used
  34602. * @returns a boolean indicating if the material is ready to be used
  34603. */
  34604. Material.prototype.isReady = function (mesh, useInstances) {
  34605. return true;
  34606. };
  34607. /**
  34608. * Specifies that the submesh is ready to be used
  34609. * @param mesh defines the mesh to check
  34610. * @param subMesh defines which submesh to check
  34611. * @param useInstances specifies that instances should be used
  34612. * @returns a boolean indicating that the submesh is ready or not
  34613. */
  34614. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34615. return false;
  34616. };
  34617. /**
  34618. * Returns the material effect
  34619. * @returns the effect associated with the material
  34620. */
  34621. Material.prototype.getEffect = function () {
  34622. return this._effect;
  34623. };
  34624. /**
  34625. * Returns the current scene
  34626. * @returns a Scene
  34627. */
  34628. Material.prototype.getScene = function () {
  34629. return this._scene;
  34630. };
  34631. /**
  34632. * Specifies if the material will require alpha blending
  34633. * @returns a boolean specifying if alpha blending is needed
  34634. */
  34635. Material.prototype.needAlphaBlending = function () {
  34636. return (this.alpha < 1.0);
  34637. };
  34638. /**
  34639. * Specifies if the mesh will require alpha blending
  34640. * @param mesh defines the mesh to check
  34641. * @returns a boolean specifying if alpha blending is needed for the mesh
  34642. */
  34643. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34644. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34645. };
  34646. /**
  34647. * Specifies if this material should be rendered in alpha test mode
  34648. * @returns a boolean specifying if an alpha test is needed.
  34649. */
  34650. Material.prototype.needAlphaTesting = function () {
  34651. return false;
  34652. };
  34653. /**
  34654. * Gets the texture used for the alpha test
  34655. * @returns the texture to use for alpha testing
  34656. */
  34657. Material.prototype.getAlphaTestTexture = function () {
  34658. return null;
  34659. };
  34660. /**
  34661. * Marks the material to indicate that it needs to be re-calculated
  34662. */
  34663. Material.prototype.markDirty = function () {
  34664. this._wasPreviouslyReady = false;
  34665. };
  34666. /** @ignore */
  34667. Material.prototype._preBind = function (effect, overrideOrientation) {
  34668. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34669. var engine = this._scene.getEngine();
  34670. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34671. var reverse = orientation === Material.ClockWiseSideOrientation;
  34672. engine.enableEffect(effect ? effect : this._effect);
  34673. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34674. return reverse;
  34675. };
  34676. /**
  34677. * Binds the material to the mesh
  34678. * @param world defines the world transformation matrix
  34679. * @param mesh defines the mesh to bind the material to
  34680. */
  34681. Material.prototype.bind = function (world, mesh) {
  34682. };
  34683. /**
  34684. * Binds the submesh to the material
  34685. * @param world defines the world transformation matrix
  34686. * @param mesh defines the mesh containing the submesh
  34687. * @param subMesh defines the submesh to bind the material to
  34688. */
  34689. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34690. };
  34691. /**
  34692. * Binds the world matrix to the material
  34693. * @param world defines the world transformation matrix
  34694. */
  34695. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34696. };
  34697. /**
  34698. * Binds the scene's uniform buffer to the effect.
  34699. * @param effect defines the effect to bind to the scene uniform buffer
  34700. * @param sceneUbo defines the uniform buffer storing scene data
  34701. */
  34702. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34703. sceneUbo.bindToEffect(effect, "Scene");
  34704. };
  34705. /**
  34706. * Binds the view matrix to the effect
  34707. * @param effect defines the effect to bind the view matrix to
  34708. */
  34709. Material.prototype.bindView = function (effect) {
  34710. if (!this._useUBO) {
  34711. effect.setMatrix("view", this.getScene().getViewMatrix());
  34712. }
  34713. else {
  34714. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34715. }
  34716. };
  34717. /**
  34718. * Binds the view projection matrix to the effect
  34719. * @param effect defines the effect to bind the view projection matrix to
  34720. */
  34721. Material.prototype.bindViewProjection = function (effect) {
  34722. if (!this._useUBO) {
  34723. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34724. }
  34725. else {
  34726. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34727. }
  34728. };
  34729. /**
  34730. * Specifies if material alpha testing should be turned on for the mesh
  34731. * @param mesh defines the mesh to check
  34732. */
  34733. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34734. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34735. };
  34736. /**
  34737. * Processes to execute after binding the material to a mesh
  34738. * @param mesh defines the rendered mesh
  34739. */
  34740. Material.prototype._afterBind = function (mesh) {
  34741. this._scene._cachedMaterial = this;
  34742. if (mesh) {
  34743. this._scene._cachedVisibility = mesh.visibility;
  34744. }
  34745. else {
  34746. this._scene._cachedVisibility = 1;
  34747. }
  34748. if (mesh) {
  34749. this.onBindObservable.notifyObservers(mesh);
  34750. }
  34751. if (this.disableDepthWrite) {
  34752. var engine = this._scene.getEngine();
  34753. this._cachedDepthWriteState = engine.getDepthWrite();
  34754. engine.setDepthWrite(false);
  34755. }
  34756. };
  34757. /**
  34758. * Unbinds the material from the mesh
  34759. */
  34760. Material.prototype.unbind = function () {
  34761. this.onUnBindObservable.notifyObservers(this);
  34762. if (this.disableDepthWrite) {
  34763. var engine = this._scene.getEngine();
  34764. engine.setDepthWrite(this._cachedDepthWriteState);
  34765. }
  34766. };
  34767. /**
  34768. * Gets the active textures from the material
  34769. * @returns an array of textures
  34770. */
  34771. Material.prototype.getActiveTextures = function () {
  34772. return [];
  34773. };
  34774. /**
  34775. * Specifies if the material uses a texture
  34776. * @param texture defines the texture to check against the material
  34777. * @returns a boolean specifying if the material uses the texture
  34778. */
  34779. Material.prototype.hasTexture = function (texture) {
  34780. return false;
  34781. };
  34782. /**
  34783. * Makes a duplicate of the material, and gives it a new name
  34784. * @param name defines the new name for the duplicated material
  34785. * @returns the cloned material
  34786. */
  34787. Material.prototype.clone = function (name) {
  34788. return null;
  34789. };
  34790. /**
  34791. * Gets the meshes bound to the material
  34792. * @returns an array of meshes bound to the material
  34793. */
  34794. Material.prototype.getBindedMeshes = function () {
  34795. var result = new Array();
  34796. for (var index = 0; index < this._scene.meshes.length; index++) {
  34797. var mesh = this._scene.meshes[index];
  34798. if (mesh.material === this) {
  34799. result.push(mesh);
  34800. }
  34801. }
  34802. return result;
  34803. };
  34804. /**
  34805. * Force shader compilation
  34806. * @param mesh defines the mesh associated with this material
  34807. * @param onCompiled defines a function to execute once the material is compiled
  34808. * @param options defines the options to configure the compilation
  34809. */
  34810. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34811. var _this = this;
  34812. var localOptions = __assign({ clipPlane: false }, options);
  34813. var subMesh = new BABYLON.BaseSubMesh();
  34814. var scene = this.getScene();
  34815. var checkReady = function () {
  34816. if (!_this._scene || !_this._scene.getEngine()) {
  34817. return;
  34818. }
  34819. if (subMesh._materialDefines) {
  34820. subMesh._materialDefines._renderId = -1;
  34821. }
  34822. var clipPlaneState = scene.clipPlane;
  34823. if (localOptions.clipPlane) {
  34824. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34825. }
  34826. if (_this.storeEffectOnSubMeshes) {
  34827. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34828. if (onCompiled) {
  34829. onCompiled(_this);
  34830. }
  34831. }
  34832. else {
  34833. setTimeout(checkReady, 16);
  34834. }
  34835. }
  34836. else {
  34837. if (_this.isReady(mesh)) {
  34838. if (onCompiled) {
  34839. onCompiled(_this);
  34840. }
  34841. }
  34842. else {
  34843. setTimeout(checkReady, 16);
  34844. }
  34845. }
  34846. if (localOptions.clipPlane) {
  34847. scene.clipPlane = clipPlaneState;
  34848. }
  34849. };
  34850. checkReady();
  34851. };
  34852. /**
  34853. * Force shader compilation
  34854. * @param mesh defines the mesh that will use this material
  34855. * @param options defines additional options for compiling the shaders
  34856. * @returns a promise that resolves when the compilation completes
  34857. */
  34858. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34859. var _this = this;
  34860. return new Promise(function (resolve) {
  34861. _this.forceCompilation(mesh, function () {
  34862. resolve();
  34863. }, options);
  34864. });
  34865. };
  34866. /**
  34867. * Marks a define in the material to indicate that it needs to be re-computed
  34868. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34869. */
  34870. Material.prototype.markAsDirty = function (flag) {
  34871. if (flag & Material.TextureDirtyFlag) {
  34872. this._markAllSubMeshesAsTexturesDirty();
  34873. }
  34874. if (flag & Material.LightDirtyFlag) {
  34875. this._markAllSubMeshesAsLightsDirty();
  34876. }
  34877. if (flag & Material.FresnelDirtyFlag) {
  34878. this._markAllSubMeshesAsFresnelDirty();
  34879. }
  34880. if (flag & Material.AttributesDirtyFlag) {
  34881. this._markAllSubMeshesAsAttributesDirty();
  34882. }
  34883. if (flag & Material.MiscDirtyFlag) {
  34884. this._markAllSubMeshesAsMiscDirty();
  34885. }
  34886. this.getScene().resetCachedMaterial();
  34887. };
  34888. /**
  34889. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34890. * @param func defines a function which checks material defines against the submeshes
  34891. */
  34892. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34893. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34894. var mesh = _a[_i];
  34895. if (!mesh.subMeshes) {
  34896. continue;
  34897. }
  34898. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34899. var subMesh = _c[_b];
  34900. if (subMesh.getMaterial() !== this) {
  34901. continue;
  34902. }
  34903. if (!subMesh._materialDefines) {
  34904. continue;
  34905. }
  34906. func(subMesh._materialDefines);
  34907. }
  34908. }
  34909. };
  34910. /**
  34911. * Indicates that image processing needs to be re-calculated for all submeshes
  34912. */
  34913. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34914. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34915. };
  34916. /**
  34917. * Indicates that textures need to be re-calculated for all submeshes
  34918. */
  34919. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34920. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34921. };
  34922. /**
  34923. * Indicates that fresnel needs to be re-calculated for all submeshes
  34924. */
  34925. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34926. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34927. };
  34928. /**
  34929. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34930. */
  34931. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34932. this._markAllSubMeshesAsDirty(function (defines) {
  34933. defines.markAsFresnelDirty();
  34934. defines.markAsMiscDirty();
  34935. });
  34936. };
  34937. /**
  34938. * Indicates that lights need to be re-calculated for all submeshes
  34939. */
  34940. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34941. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34942. };
  34943. /**
  34944. * Indicates that attributes need to be re-calculated for all submeshes
  34945. */
  34946. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34947. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34948. };
  34949. /**
  34950. * Indicates that misc needs to be re-calculated for all submeshes
  34951. */
  34952. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34953. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34954. };
  34955. /**
  34956. * Indicates that textures and misc need to be re-calculated for all submeshes
  34957. */
  34958. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34959. this._markAllSubMeshesAsDirty(function (defines) {
  34960. defines.markAsTexturesDirty();
  34961. defines.markAsMiscDirty();
  34962. });
  34963. };
  34964. /**
  34965. * Disposes the material
  34966. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34967. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34968. */
  34969. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34970. // Animations
  34971. this.getScene().stopAnimation(this);
  34972. this.getScene().freeProcessedMaterials();
  34973. // Remove from scene
  34974. var index = this._scene.materials.indexOf(this);
  34975. if (index >= 0) {
  34976. this._scene.materials.splice(index, 1);
  34977. }
  34978. // Remove from meshes
  34979. for (index = 0; index < this._scene.meshes.length; index++) {
  34980. var mesh = this._scene.meshes[index];
  34981. if (mesh.material === this) {
  34982. mesh.material = null;
  34983. if (mesh.geometry) {
  34984. var geometry = (mesh.geometry);
  34985. if (this.storeEffectOnSubMeshes) {
  34986. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34987. var subMesh = _a[_i];
  34988. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34989. if (forceDisposeEffect && subMesh._materialEffect) {
  34990. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34991. }
  34992. }
  34993. }
  34994. else {
  34995. geometry._releaseVertexArrayObject(this._effect);
  34996. }
  34997. }
  34998. }
  34999. }
  35000. this._uniformBuffer.dispose();
  35001. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35002. if (forceDisposeEffect && this._effect) {
  35003. if (!this.storeEffectOnSubMeshes) {
  35004. this._scene.getEngine()._releaseEffect(this._effect);
  35005. }
  35006. this._effect = null;
  35007. }
  35008. // Callback
  35009. this.onDisposeObservable.notifyObservers(this);
  35010. this.onDisposeObservable.clear();
  35011. this.onBindObservable.clear();
  35012. this.onUnBindObservable.clear();
  35013. };
  35014. /**
  35015. * Serializes this material
  35016. * @returns the serialized material object
  35017. */
  35018. Material.prototype.serialize = function () {
  35019. return BABYLON.SerializationHelper.Serialize(this);
  35020. };
  35021. /**
  35022. * Creates a MultiMaterial from parsed MultiMaterial data.
  35023. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35024. * @param scene defines the hosting scene
  35025. * @returns a new MultiMaterial
  35026. */
  35027. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35028. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35029. multiMaterial.id = parsedMultiMaterial.id;
  35030. if (BABYLON.Tags) {
  35031. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35032. }
  35033. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35034. var subMatId = parsedMultiMaterial.materials[matIndex];
  35035. if (subMatId) {
  35036. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35037. }
  35038. else {
  35039. multiMaterial.subMaterials.push(null);
  35040. }
  35041. }
  35042. return multiMaterial;
  35043. };
  35044. /**
  35045. * Creates a material from parsed material data
  35046. * @param parsedMaterial defines parsed material data
  35047. * @param scene defines the hosting scene
  35048. * @param rootUrl defines the root URL to use to load textures
  35049. * @returns a new material
  35050. */
  35051. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35052. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35053. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35054. }
  35055. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35056. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35057. if (!BABYLON.LegacyPBRMaterial) {
  35058. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35059. return;
  35060. }
  35061. }
  35062. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35063. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35064. ;
  35065. };
  35066. // Triangle views
  35067. Material._TriangleFillMode = 0;
  35068. Material._WireFrameFillMode = 1;
  35069. Material._PointFillMode = 2;
  35070. // Draw modes
  35071. Material._PointListDrawMode = 3;
  35072. Material._LineListDrawMode = 4;
  35073. Material._LineLoopDrawMode = 5;
  35074. Material._LineStripDrawMode = 6;
  35075. Material._TriangleStripDrawMode = 7;
  35076. Material._TriangleFanDrawMode = 8;
  35077. /**
  35078. * Stores the clock-wise side orientation
  35079. */
  35080. Material._ClockWiseSideOrientation = 0;
  35081. /**
  35082. * Stores the counter clock-wise side orientation
  35083. */
  35084. Material._CounterClockWiseSideOrientation = 1;
  35085. /**
  35086. * The dirty texture flag value
  35087. */
  35088. Material._TextureDirtyFlag = 1;
  35089. /**
  35090. * The dirty light flag value
  35091. */
  35092. Material._LightDirtyFlag = 2;
  35093. /**
  35094. * The dirty fresnel flag value
  35095. */
  35096. Material._FresnelDirtyFlag = 4;
  35097. /**
  35098. * The dirty attribute flag value
  35099. */
  35100. Material._AttributesDirtyFlag = 8;
  35101. /**
  35102. * The dirty misc flag value
  35103. */
  35104. Material._MiscDirtyFlag = 16;
  35105. __decorate([
  35106. BABYLON.serialize()
  35107. ], Material.prototype, "id", void 0);
  35108. __decorate([
  35109. BABYLON.serialize()
  35110. ], Material.prototype, "name", void 0);
  35111. __decorate([
  35112. BABYLON.serialize()
  35113. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35114. __decorate([
  35115. BABYLON.serialize()
  35116. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35117. __decorate([
  35118. BABYLON.serialize()
  35119. ], Material.prototype, "state", void 0);
  35120. __decorate([
  35121. BABYLON.serialize("alpha")
  35122. ], Material.prototype, "_alpha", void 0);
  35123. __decorate([
  35124. BABYLON.serialize("backFaceCulling")
  35125. ], Material.prototype, "_backFaceCulling", void 0);
  35126. __decorate([
  35127. BABYLON.serialize()
  35128. ], Material.prototype, "sideOrientation", void 0);
  35129. __decorate([
  35130. BABYLON.serialize("alphaMode")
  35131. ], Material.prototype, "_alphaMode", void 0);
  35132. __decorate([
  35133. BABYLON.serialize()
  35134. ], Material.prototype, "_needDepthPrePass", void 0);
  35135. __decorate([
  35136. BABYLON.serialize()
  35137. ], Material.prototype, "disableDepthWrite", void 0);
  35138. __decorate([
  35139. BABYLON.serialize()
  35140. ], Material.prototype, "forceDepthWrite", void 0);
  35141. __decorate([
  35142. BABYLON.serialize()
  35143. ], Material.prototype, "separateCullingPass", void 0);
  35144. __decorate([
  35145. BABYLON.serialize("fogEnabled")
  35146. ], Material.prototype, "_fogEnabled", void 0);
  35147. __decorate([
  35148. BABYLON.serialize()
  35149. ], Material.prototype, "pointSize", void 0);
  35150. __decorate([
  35151. BABYLON.serialize()
  35152. ], Material.prototype, "zOffset", void 0);
  35153. __decorate([
  35154. BABYLON.serialize()
  35155. ], Material.prototype, "wireframe", null);
  35156. __decorate([
  35157. BABYLON.serialize()
  35158. ], Material.prototype, "pointsCloud", null);
  35159. __decorate([
  35160. BABYLON.serialize()
  35161. ], Material.prototype, "fillMode", null);
  35162. return Material;
  35163. }());
  35164. BABYLON.Material = Material;
  35165. })(BABYLON || (BABYLON = {}));
  35166. //# sourceMappingURL=babylon.material.js.map
  35167. "use strict";
  35168. var BABYLON;
  35169. (function (BABYLON) {
  35170. var UniformBuffer = /** @class */ (function () {
  35171. /**
  35172. * Uniform buffer objects.
  35173. *
  35174. * Handles blocks of uniform on the GPU.
  35175. *
  35176. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35177. *
  35178. * For more information, please refer to :
  35179. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35180. */
  35181. function UniformBuffer(engine, data, dynamic) {
  35182. this._engine = engine;
  35183. this._noUBO = !engine.supportsUniformBuffers;
  35184. this._dynamic = dynamic;
  35185. this._data = data || [];
  35186. this._uniformLocations = {};
  35187. this._uniformSizes = {};
  35188. this._uniformLocationPointer = 0;
  35189. this._needSync = false;
  35190. if (this._noUBO) {
  35191. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35192. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35193. this.updateFloat = this._updateFloatForEffect;
  35194. this.updateFloat2 = this._updateFloat2ForEffect;
  35195. this.updateFloat3 = this._updateFloat3ForEffect;
  35196. this.updateFloat4 = this._updateFloat4ForEffect;
  35197. this.updateMatrix = this._updateMatrixForEffect;
  35198. this.updateVector3 = this._updateVector3ForEffect;
  35199. this.updateVector4 = this._updateVector4ForEffect;
  35200. this.updateColor3 = this._updateColor3ForEffect;
  35201. this.updateColor4 = this._updateColor4ForEffect;
  35202. }
  35203. else {
  35204. this._engine._uniformBuffers.push(this);
  35205. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35206. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35207. this.updateFloat = this._updateFloatForUniform;
  35208. this.updateFloat2 = this._updateFloat2ForUniform;
  35209. this.updateFloat3 = this._updateFloat3ForUniform;
  35210. this.updateFloat4 = this._updateFloat4ForUniform;
  35211. this.updateMatrix = this._updateMatrixForUniform;
  35212. this.updateVector3 = this._updateVector3ForUniform;
  35213. this.updateVector4 = this._updateVector4ForUniform;
  35214. this.updateColor3 = this._updateColor3ForUniform;
  35215. this.updateColor4 = this._updateColor4ForUniform;
  35216. }
  35217. }
  35218. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35219. // Properties
  35220. /**
  35221. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35222. * or just falling back on setUniformXXX calls.
  35223. */
  35224. get: function () {
  35225. return !this._noUBO;
  35226. },
  35227. enumerable: true,
  35228. configurable: true
  35229. });
  35230. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35231. /**
  35232. * Indicates if the WebGL underlying uniform buffer is in sync
  35233. * with the javascript cache data.
  35234. */
  35235. get: function () {
  35236. return !this._needSync;
  35237. },
  35238. enumerable: true,
  35239. configurable: true
  35240. });
  35241. /**
  35242. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35243. * Also, a dynamic UniformBuffer will disable cache verification and always
  35244. * update the underlying WebGL uniform buffer to the GPU.
  35245. */
  35246. UniformBuffer.prototype.isDynamic = function () {
  35247. return this._dynamic !== undefined;
  35248. };
  35249. /**
  35250. * The data cache on JS side.
  35251. */
  35252. UniformBuffer.prototype.getData = function () {
  35253. return this._bufferData;
  35254. };
  35255. /**
  35256. * The underlying WebGL Uniform buffer.
  35257. */
  35258. UniformBuffer.prototype.getBuffer = function () {
  35259. return this._buffer;
  35260. };
  35261. /**
  35262. * std140 layout specifies how to align data within an UBO structure.
  35263. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35264. * for specs.
  35265. */
  35266. UniformBuffer.prototype._fillAlignment = function (size) {
  35267. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35268. // and 4x4 matrices
  35269. // TODO : change if other types are used
  35270. var alignment;
  35271. if (size <= 2) {
  35272. alignment = size;
  35273. }
  35274. else {
  35275. alignment = 4;
  35276. }
  35277. if ((this._uniformLocationPointer % alignment) !== 0) {
  35278. var oldPointer = this._uniformLocationPointer;
  35279. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35280. var diff = this._uniformLocationPointer - oldPointer;
  35281. for (var i = 0; i < diff; i++) {
  35282. this._data.push(0);
  35283. }
  35284. }
  35285. };
  35286. /**
  35287. * Adds an uniform in the buffer.
  35288. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35289. * for the layout to be correct !
  35290. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35291. * @param {number|number[]} size Data size, or data directly.
  35292. */
  35293. UniformBuffer.prototype.addUniform = function (name, size) {
  35294. if (this._noUBO) {
  35295. return;
  35296. }
  35297. if (this._uniformLocations[name] !== undefined) {
  35298. // Already existing uniform
  35299. return;
  35300. }
  35301. // This function must be called in the order of the shader layout !
  35302. // size can be the size of the uniform, or data directly
  35303. var data;
  35304. if (size instanceof Array) {
  35305. data = size;
  35306. size = data.length;
  35307. }
  35308. else {
  35309. size = size;
  35310. data = [];
  35311. // Fill with zeros
  35312. for (var i = 0; i < size; i++) {
  35313. data.push(0);
  35314. }
  35315. }
  35316. this._fillAlignment(size);
  35317. this._uniformSizes[name] = size;
  35318. this._uniformLocations[name] = this._uniformLocationPointer;
  35319. this._uniformLocationPointer += size;
  35320. for (var i = 0; i < size; i++) {
  35321. this._data.push(data[i]);
  35322. }
  35323. this._needSync = true;
  35324. };
  35325. /**
  35326. * Wrapper for addUniform.
  35327. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35328. * @param {Matrix} mat A 4x4 matrix.
  35329. */
  35330. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35331. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35332. };
  35333. /**
  35334. * Wrapper for addUniform.
  35335. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35336. * @param {number} x
  35337. * @param {number} y
  35338. */
  35339. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35340. var temp = [x, y];
  35341. this.addUniform(name, temp);
  35342. };
  35343. /**
  35344. * Wrapper for addUniform.
  35345. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35346. * @param {number} x
  35347. * @param {number} y
  35348. * @param {number} z
  35349. */
  35350. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35351. var temp = [x, y, z];
  35352. this.addUniform(name, temp);
  35353. };
  35354. /**
  35355. * Wrapper for addUniform.
  35356. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35357. * @param {Color3} color
  35358. */
  35359. UniformBuffer.prototype.addColor3 = function (name, color) {
  35360. var temp = new Array();
  35361. color.toArray(temp);
  35362. this.addUniform(name, temp);
  35363. };
  35364. /**
  35365. * Wrapper for addUniform.
  35366. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35367. * @param {Color3} color
  35368. * @param {number} alpha
  35369. */
  35370. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35371. var temp = new Array();
  35372. color.toArray(temp);
  35373. temp.push(alpha);
  35374. this.addUniform(name, temp);
  35375. };
  35376. /**
  35377. * Wrapper for addUniform.
  35378. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35379. * @param {Vector3} vector
  35380. */
  35381. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35382. var temp = new Array();
  35383. vector.toArray(temp);
  35384. this.addUniform(name, temp);
  35385. };
  35386. /**
  35387. * Wrapper for addUniform.
  35388. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35389. */
  35390. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35391. this.addUniform(name, 12);
  35392. };
  35393. /**
  35394. * Wrapper for addUniform.
  35395. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35396. */
  35397. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35398. this.addUniform(name, 8);
  35399. };
  35400. /**
  35401. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35402. */
  35403. UniformBuffer.prototype.create = function () {
  35404. if (this._noUBO) {
  35405. return;
  35406. }
  35407. if (this._buffer) {
  35408. return; // nothing to do
  35409. }
  35410. // See spec, alignment must be filled as a vec4
  35411. this._fillAlignment(4);
  35412. this._bufferData = new Float32Array(this._data);
  35413. this._rebuild();
  35414. this._needSync = true;
  35415. };
  35416. UniformBuffer.prototype._rebuild = function () {
  35417. if (this._noUBO) {
  35418. return;
  35419. }
  35420. if (this._dynamic) {
  35421. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35422. }
  35423. else {
  35424. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35425. }
  35426. };
  35427. /**
  35428. * Updates the WebGL Uniform Buffer on the GPU.
  35429. * If the `dynamic` flag is set to true, no cache comparison is done.
  35430. * Otherwise, the buffer will be updated only if the cache differs.
  35431. */
  35432. UniformBuffer.prototype.update = function () {
  35433. if (!this._buffer) {
  35434. this.create();
  35435. return;
  35436. }
  35437. if (!this._dynamic && !this._needSync) {
  35438. return;
  35439. }
  35440. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35441. this._needSync = false;
  35442. };
  35443. /**
  35444. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35445. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35446. * @param {number[]|Float32Array} data Flattened data
  35447. * @param {number} size Size of the data.
  35448. */
  35449. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35450. var location = this._uniformLocations[uniformName];
  35451. if (location === undefined) {
  35452. if (this._buffer) {
  35453. // Cannot add an uniform if the buffer is already created
  35454. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35455. return;
  35456. }
  35457. this.addUniform(uniformName, size);
  35458. location = this._uniformLocations[uniformName];
  35459. }
  35460. if (!this._buffer) {
  35461. this.create();
  35462. }
  35463. if (!this._dynamic) {
  35464. // Cache for static uniform buffers
  35465. var changed = false;
  35466. for (var i = 0; i < size; i++) {
  35467. if (this._bufferData[location + i] !== data[i]) {
  35468. changed = true;
  35469. this._bufferData[location + i] = data[i];
  35470. }
  35471. }
  35472. this._needSync = this._needSync || changed;
  35473. }
  35474. else {
  35475. // No cache for dynamic
  35476. for (var i = 0; i < size; i++) {
  35477. this._bufferData[location + i] = data[i];
  35478. }
  35479. }
  35480. };
  35481. // Update methods
  35482. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35483. // To match std140, matrix must be realigned
  35484. for (var i = 0; i < 3; i++) {
  35485. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35486. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35487. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35488. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35489. }
  35490. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35491. };
  35492. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35493. this._currentEffect.setMatrix3x3(name, matrix);
  35494. };
  35495. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35496. this._currentEffect.setMatrix2x2(name, matrix);
  35497. };
  35498. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35499. // To match std140, matrix must be realigned
  35500. for (var i = 0; i < 2; i++) {
  35501. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35502. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35503. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35504. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35505. }
  35506. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35507. };
  35508. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35509. this._currentEffect.setFloat(name, x);
  35510. };
  35511. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35512. UniformBuffer._tempBuffer[0] = x;
  35513. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35514. };
  35515. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35516. if (suffix === void 0) { suffix = ""; }
  35517. this._currentEffect.setFloat2(name + suffix, x, y);
  35518. };
  35519. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35520. if (suffix === void 0) { suffix = ""; }
  35521. UniformBuffer._tempBuffer[0] = x;
  35522. UniformBuffer._tempBuffer[1] = y;
  35523. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35524. };
  35525. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35526. if (suffix === void 0) { suffix = ""; }
  35527. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35528. };
  35529. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35530. if (suffix === void 0) { suffix = ""; }
  35531. UniformBuffer._tempBuffer[0] = x;
  35532. UniformBuffer._tempBuffer[1] = y;
  35533. UniformBuffer._tempBuffer[2] = z;
  35534. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35535. };
  35536. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35537. if (suffix === void 0) { suffix = ""; }
  35538. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35539. };
  35540. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35541. if (suffix === void 0) { suffix = ""; }
  35542. UniformBuffer._tempBuffer[0] = x;
  35543. UniformBuffer._tempBuffer[1] = y;
  35544. UniformBuffer._tempBuffer[2] = z;
  35545. UniformBuffer._tempBuffer[3] = w;
  35546. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35547. };
  35548. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35549. this._currentEffect.setMatrix(name, mat);
  35550. };
  35551. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35552. this.updateUniform(name, mat.toArray(), 16);
  35553. };
  35554. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35555. this._currentEffect.setVector3(name, vector);
  35556. };
  35557. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35558. vector.toArray(UniformBuffer._tempBuffer);
  35559. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35560. };
  35561. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35562. this._currentEffect.setVector4(name, vector);
  35563. };
  35564. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35565. vector.toArray(UniformBuffer._tempBuffer);
  35566. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35567. };
  35568. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35569. if (suffix === void 0) { suffix = ""; }
  35570. this._currentEffect.setColor3(name + suffix, color);
  35571. };
  35572. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35573. if (suffix === void 0) { suffix = ""; }
  35574. color.toArray(UniformBuffer._tempBuffer);
  35575. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35576. };
  35577. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35578. if (suffix === void 0) { suffix = ""; }
  35579. this._currentEffect.setColor4(name + suffix, color, alpha);
  35580. };
  35581. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35582. if (suffix === void 0) { suffix = ""; }
  35583. color.toArray(UniformBuffer._tempBuffer);
  35584. UniformBuffer._tempBuffer[3] = alpha;
  35585. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35586. };
  35587. /**
  35588. * Sets a sampler uniform on the effect.
  35589. * @param {string} name Name of the sampler.
  35590. * @param {Texture} texture
  35591. */
  35592. UniformBuffer.prototype.setTexture = function (name, texture) {
  35593. this._currentEffect.setTexture(name, texture);
  35594. };
  35595. /**
  35596. * Directly updates the value of the uniform in the cache AND on the GPU.
  35597. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35598. * @param {number[]|Float32Array} data Flattened data
  35599. */
  35600. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35601. this.updateUniform(uniformName, data, data.length);
  35602. this.update();
  35603. };
  35604. /**
  35605. * Binds this uniform buffer to an effect.
  35606. * @param {Effect} effect
  35607. * @param {string} name Name of the uniform block in the shader.
  35608. */
  35609. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35610. this._currentEffect = effect;
  35611. if (this._noUBO || !this._buffer) {
  35612. return;
  35613. }
  35614. effect.bindUniformBuffer(this._buffer, name);
  35615. };
  35616. /**
  35617. * Disposes the uniform buffer.
  35618. */
  35619. UniformBuffer.prototype.dispose = function () {
  35620. if (this._noUBO) {
  35621. return;
  35622. }
  35623. var index = this._engine._uniformBuffers.indexOf(this);
  35624. if (index !== -1) {
  35625. this._engine._uniformBuffers.splice(index, 1);
  35626. }
  35627. if (!this._buffer) {
  35628. return;
  35629. }
  35630. if (this._engine._releaseBuffer(this._buffer)) {
  35631. this._buffer = null;
  35632. }
  35633. };
  35634. // Pool for avoiding memory leaks
  35635. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35636. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35637. return UniformBuffer;
  35638. }());
  35639. BABYLON.UniformBuffer = UniformBuffer;
  35640. })(BABYLON || (BABYLON = {}));
  35641. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35642. "use strict";
  35643. var BABYLON;
  35644. (function (BABYLON) {
  35645. /**
  35646. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35647. */
  35648. var VertexData = /** @class */ (function () {
  35649. function VertexData() {
  35650. }
  35651. /**
  35652. * Uses the passed data array to set the set the values for the specified kind of data
  35653. * @param data a linear array of floating numbers
  35654. * @param kind the type of data that is being set, eg positions, colors etc
  35655. */
  35656. VertexData.prototype.set = function (data, kind) {
  35657. switch (kind) {
  35658. case BABYLON.VertexBuffer.PositionKind:
  35659. this.positions = data;
  35660. break;
  35661. case BABYLON.VertexBuffer.NormalKind:
  35662. this.normals = data;
  35663. break;
  35664. case BABYLON.VertexBuffer.TangentKind:
  35665. this.tangents = data;
  35666. break;
  35667. case BABYLON.VertexBuffer.UVKind:
  35668. this.uvs = data;
  35669. break;
  35670. case BABYLON.VertexBuffer.UV2Kind:
  35671. this.uvs2 = data;
  35672. break;
  35673. case BABYLON.VertexBuffer.UV3Kind:
  35674. this.uvs3 = data;
  35675. break;
  35676. case BABYLON.VertexBuffer.UV4Kind:
  35677. this.uvs4 = data;
  35678. break;
  35679. case BABYLON.VertexBuffer.UV5Kind:
  35680. this.uvs5 = data;
  35681. break;
  35682. case BABYLON.VertexBuffer.UV6Kind:
  35683. this.uvs6 = data;
  35684. break;
  35685. case BABYLON.VertexBuffer.ColorKind:
  35686. this.colors = data;
  35687. break;
  35688. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35689. this.matricesIndices = data;
  35690. break;
  35691. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35692. this.matricesWeights = data;
  35693. break;
  35694. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35695. this.matricesIndicesExtra = data;
  35696. break;
  35697. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35698. this.matricesWeightsExtra = data;
  35699. break;
  35700. }
  35701. };
  35702. /**
  35703. * Associates the vertexData to the passed Mesh.
  35704. * Sets it as updatable or not (default `false`)
  35705. * @param mesh the mesh the vertexData is applied to
  35706. * @param updatable when used and having the value true allows new data to update the vertexData
  35707. * @returns the VertexData
  35708. */
  35709. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35710. this._applyTo(mesh, updatable);
  35711. return this;
  35712. };
  35713. /**
  35714. * Associates the vertexData to the passed Geometry.
  35715. * Sets it as updatable or not (default `false`)
  35716. * @param geometry the geometry the vertexData is applied to
  35717. * @param updatable when used and having the value true allows new data to update the vertexData
  35718. * @returns VertexData
  35719. */
  35720. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35721. this._applyTo(geometry, updatable);
  35722. return this;
  35723. };
  35724. /**
  35725. * Updates the associated mesh
  35726. * @param mesh the mesh to be updated
  35727. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35728. * @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
  35729. * @returns VertexData
  35730. */
  35731. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35732. this._update(mesh);
  35733. return this;
  35734. };
  35735. /**
  35736. * Updates the associated geometry
  35737. * @param geometry the geometry to be updated
  35738. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35739. * @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
  35740. * @returns VertexData.
  35741. */
  35742. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35743. this._update(geometry);
  35744. return this;
  35745. };
  35746. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35747. if (updatable === void 0) { updatable = false; }
  35748. if (this.positions) {
  35749. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35750. }
  35751. if (this.normals) {
  35752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35753. }
  35754. if (this.tangents) {
  35755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35756. }
  35757. if (this.uvs) {
  35758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35759. }
  35760. if (this.uvs2) {
  35761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35762. }
  35763. if (this.uvs3) {
  35764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35765. }
  35766. if (this.uvs4) {
  35767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35768. }
  35769. if (this.uvs5) {
  35770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35771. }
  35772. if (this.uvs6) {
  35773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35774. }
  35775. if (this.colors) {
  35776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35777. }
  35778. if (this.matricesIndices) {
  35779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35780. }
  35781. if (this.matricesWeights) {
  35782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35783. }
  35784. if (this.matricesIndicesExtra) {
  35785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35786. }
  35787. if (this.matricesWeightsExtra) {
  35788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35789. }
  35790. if (this.indices) {
  35791. meshOrGeometry.setIndices(this.indices, null, updatable);
  35792. }
  35793. return this;
  35794. };
  35795. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35796. if (this.positions) {
  35797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35798. }
  35799. if (this.normals) {
  35800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35801. }
  35802. if (this.tangents) {
  35803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35804. }
  35805. if (this.uvs) {
  35806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35807. }
  35808. if (this.uvs2) {
  35809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35810. }
  35811. if (this.uvs3) {
  35812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35813. }
  35814. if (this.uvs4) {
  35815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35816. }
  35817. if (this.uvs5) {
  35818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35819. }
  35820. if (this.uvs6) {
  35821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35822. }
  35823. if (this.colors) {
  35824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35825. }
  35826. if (this.matricesIndices) {
  35827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35828. }
  35829. if (this.matricesWeights) {
  35830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35831. }
  35832. if (this.matricesIndicesExtra) {
  35833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35834. }
  35835. if (this.matricesWeightsExtra) {
  35836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35837. }
  35838. if (this.indices) {
  35839. meshOrGeometry.setIndices(this.indices, null);
  35840. }
  35841. return this;
  35842. };
  35843. /**
  35844. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35845. * @param matrix the transforming matrix
  35846. * @returns the VertexData
  35847. */
  35848. VertexData.prototype.transform = function (matrix) {
  35849. var transformed = BABYLON.Vector3.Zero();
  35850. var index;
  35851. if (this.positions) {
  35852. var position = BABYLON.Vector3.Zero();
  35853. for (index = 0; index < this.positions.length; index += 3) {
  35854. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35855. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35856. this.positions[index] = transformed.x;
  35857. this.positions[index + 1] = transformed.y;
  35858. this.positions[index + 2] = transformed.z;
  35859. }
  35860. }
  35861. if (this.normals) {
  35862. var normal = BABYLON.Vector3.Zero();
  35863. for (index = 0; index < this.normals.length; index += 3) {
  35864. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35865. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35866. this.normals[index] = transformed.x;
  35867. this.normals[index + 1] = transformed.y;
  35868. this.normals[index + 2] = transformed.z;
  35869. }
  35870. }
  35871. if (this.tangents) {
  35872. var tangent = BABYLON.Vector4.Zero();
  35873. var tangentTransformed = BABYLON.Vector4.Zero();
  35874. for (index = 0; index < this.tangents.length; index += 4) {
  35875. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35876. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35877. this.tangents[index] = tangentTransformed.x;
  35878. this.tangents[index + 1] = tangentTransformed.y;
  35879. this.tangents[index + 2] = tangentTransformed.z;
  35880. this.tangents[index + 3] = tangentTransformed.w;
  35881. }
  35882. }
  35883. return this;
  35884. };
  35885. /**
  35886. * Merges the passed VertexData into the current one
  35887. * @param other the VertexData to be merged into the current one
  35888. * @returns the modified VertexData
  35889. */
  35890. VertexData.prototype.merge = function (other) {
  35891. this._validate();
  35892. other._validate();
  35893. if (!this.normals !== !other.normals ||
  35894. !this.tangents !== !other.tangents ||
  35895. !this.uvs !== !other.uvs ||
  35896. !this.uvs2 !== !other.uvs2 ||
  35897. !this.uvs3 !== !other.uvs3 ||
  35898. !this.uvs4 !== !other.uvs4 ||
  35899. !this.uvs5 !== !other.uvs5 ||
  35900. !this.uvs6 !== !other.uvs6 ||
  35901. !this.colors !== !other.colors ||
  35902. !this.matricesIndices !== !other.matricesIndices ||
  35903. !this.matricesWeights !== !other.matricesWeights ||
  35904. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35905. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35906. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35907. }
  35908. if (other.indices) {
  35909. if (!this.indices) {
  35910. this.indices = [];
  35911. }
  35912. var offset = this.positions ? this.positions.length / 3 : 0;
  35913. for (var index = 0; index < other.indices.length; index++) {
  35914. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35915. this.indices.push(other.indices[index] + offset);
  35916. }
  35917. }
  35918. this.positions = this._mergeElement(this.positions, other.positions);
  35919. this.normals = this._mergeElement(this.normals, other.normals);
  35920. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35921. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35922. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35923. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35924. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35925. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35926. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35927. this.colors = this._mergeElement(this.colors, other.colors);
  35928. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35929. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35930. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35931. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35932. return this;
  35933. };
  35934. VertexData.prototype._mergeElement = function (source, other) {
  35935. if (!source) {
  35936. return other;
  35937. }
  35938. if (!other) {
  35939. return source;
  35940. }
  35941. var len = other.length + source.length;
  35942. var isSrcTypedArray = source instanceof Float32Array;
  35943. var isOthTypedArray = other instanceof Float32Array;
  35944. // use non-loop method when the source is Float32Array
  35945. if (isSrcTypedArray) {
  35946. var ret32 = new Float32Array(len);
  35947. ret32.set(source);
  35948. ret32.set(other, source.length);
  35949. return ret32;
  35950. // source is number[], when other is also use concat
  35951. }
  35952. else if (!isOthTypedArray) {
  35953. return source.concat(other);
  35954. // source is a number[], but other is a Float32Array, loop required
  35955. }
  35956. else {
  35957. var ret = source.slice(0); // copy source to a separate array
  35958. for (var i = 0, len = other.length; i < len; i++) {
  35959. ret.push(other[i]);
  35960. }
  35961. return ret;
  35962. }
  35963. };
  35964. VertexData.prototype._validate = function () {
  35965. if (!this.positions) {
  35966. throw new Error("Positions are required");
  35967. }
  35968. var getElementCount = function (kind, values) {
  35969. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35970. if ((values.length % stride) !== 0) {
  35971. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35972. }
  35973. return values.length / stride;
  35974. };
  35975. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35976. var validateElementCount = function (kind, values) {
  35977. var elementCount = getElementCount(kind, values);
  35978. if (elementCount !== positionsElementCount) {
  35979. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35980. }
  35981. };
  35982. if (this.normals)
  35983. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35984. if (this.tangents)
  35985. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35986. if (this.uvs)
  35987. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35988. if (this.uvs2)
  35989. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35990. if (this.uvs3)
  35991. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35992. if (this.uvs4)
  35993. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35994. if (this.uvs5)
  35995. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35996. if (this.uvs6)
  35997. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35998. if (this.colors)
  35999. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36000. if (this.matricesIndices)
  36001. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36002. if (this.matricesWeights)
  36003. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36004. if (this.matricesIndicesExtra)
  36005. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36006. if (this.matricesWeightsExtra)
  36007. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36008. };
  36009. /**
  36010. * Serializes the VertexData
  36011. * @returns a serialized object
  36012. */
  36013. VertexData.prototype.serialize = function () {
  36014. var serializationObject = this.serialize();
  36015. if (this.positions) {
  36016. serializationObject.positions = this.positions;
  36017. }
  36018. if (this.normals) {
  36019. serializationObject.normals = this.normals;
  36020. }
  36021. if (this.tangents) {
  36022. serializationObject.tangents = this.tangents;
  36023. }
  36024. if (this.uvs) {
  36025. serializationObject.uvs = this.uvs;
  36026. }
  36027. if (this.uvs2) {
  36028. serializationObject.uvs2 = this.uvs2;
  36029. }
  36030. if (this.uvs3) {
  36031. serializationObject.uvs3 = this.uvs3;
  36032. }
  36033. if (this.uvs4) {
  36034. serializationObject.uvs4 = this.uvs4;
  36035. }
  36036. if (this.uvs5) {
  36037. serializationObject.uvs5 = this.uvs5;
  36038. }
  36039. if (this.uvs6) {
  36040. serializationObject.uvs6 = this.uvs6;
  36041. }
  36042. if (this.colors) {
  36043. serializationObject.colors = this.colors;
  36044. }
  36045. if (this.matricesIndices) {
  36046. serializationObject.matricesIndices = this.matricesIndices;
  36047. serializationObject.matricesIndices._isExpanded = true;
  36048. }
  36049. if (this.matricesWeights) {
  36050. serializationObject.matricesWeights = this.matricesWeights;
  36051. }
  36052. if (this.matricesIndicesExtra) {
  36053. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36054. serializationObject.matricesIndicesExtra._isExpanded = true;
  36055. }
  36056. if (this.matricesWeightsExtra) {
  36057. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36058. }
  36059. serializationObject.indices = this.indices;
  36060. return serializationObject;
  36061. };
  36062. // Statics
  36063. /**
  36064. * Extracts the vertexData from a mesh
  36065. * @param mesh the mesh from which to extract the VertexData
  36066. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36067. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36068. * @returns the object VertexData associated to the passed mesh
  36069. */
  36070. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36071. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36072. };
  36073. /**
  36074. * Extracts the vertexData from the geometry
  36075. * @param geometry the geometry from which to extract the VertexData
  36076. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36077. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36078. * @returns the object VertexData associated to the passed mesh
  36079. */
  36080. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36081. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36082. };
  36083. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36084. var result = new VertexData();
  36085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36086. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36087. }
  36088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36089. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36090. }
  36091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36092. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36093. }
  36094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36095. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36096. }
  36097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36098. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36099. }
  36100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36101. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36102. }
  36103. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36104. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36105. }
  36106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36107. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36108. }
  36109. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36110. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36111. }
  36112. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36113. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36114. }
  36115. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36116. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36117. }
  36118. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36119. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36120. }
  36121. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36122. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36123. }
  36124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36125. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36126. }
  36127. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36128. return result;
  36129. };
  36130. /**
  36131. * Creates the VertexData for a Ribbon
  36132. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36133. * * pathArray array of paths, each of which an array of successive Vector3
  36134. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36135. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36136. * * 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
  36137. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36138. * * 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)
  36139. * * 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)
  36140. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36141. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36142. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36143. * @returns the VertexData of the ribbon
  36144. */
  36145. VertexData.CreateRibbon = function (options) {
  36146. var pathArray = options.pathArray;
  36147. var closeArray = options.closeArray || false;
  36148. var closePath = options.closePath || false;
  36149. var invertUV = options.invertUV || false;
  36150. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36151. var offset = options.offset || defaultOffset;
  36152. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36153. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36154. var customUV = options.uvs;
  36155. var customColors = options.colors;
  36156. var positions = [];
  36157. var indices = [];
  36158. var normals = [];
  36159. var uvs = [];
  36160. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36161. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36162. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36163. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36164. var minlg; // minimal length among all paths from pathArray
  36165. var lg = []; // array of path lengths : nb of vertex per path
  36166. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36167. var p; // path iterator
  36168. var i; // point iterator
  36169. var j; // point iterator
  36170. // if single path in pathArray
  36171. if (pathArray.length < 2) {
  36172. var ar1 = [];
  36173. var ar2 = [];
  36174. for (i = 0; i < pathArray[0].length - offset; i++) {
  36175. ar1.push(pathArray[0][i]);
  36176. ar2.push(pathArray[0][i + offset]);
  36177. }
  36178. pathArray = [ar1, ar2];
  36179. }
  36180. // positions and horizontal distances (u)
  36181. var idc = 0;
  36182. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36183. var path;
  36184. var l;
  36185. minlg = pathArray[0].length;
  36186. var vectlg;
  36187. var dist;
  36188. for (p = 0; p < pathArray.length; p++) {
  36189. uTotalDistance[p] = 0;
  36190. us[p] = [0];
  36191. path = pathArray[p];
  36192. l = path.length;
  36193. minlg = (minlg < l) ? minlg : l;
  36194. j = 0;
  36195. while (j < l) {
  36196. positions.push(path[j].x, path[j].y, path[j].z);
  36197. if (j > 0) {
  36198. vectlg = path[j].subtract(path[j - 1]).length();
  36199. dist = vectlg + uTotalDistance[p];
  36200. us[p].push(dist);
  36201. uTotalDistance[p] = dist;
  36202. }
  36203. j++;
  36204. }
  36205. if (closePath) {
  36206. j--;
  36207. positions.push(path[0].x, path[0].y, path[0].z);
  36208. vectlg = path[j].subtract(path[0]).length();
  36209. dist = vectlg + uTotalDistance[p];
  36210. us[p].push(dist);
  36211. uTotalDistance[p] = dist;
  36212. }
  36213. lg[p] = l + closePathCorr;
  36214. idx[p] = idc;
  36215. idc += (l + closePathCorr);
  36216. }
  36217. // vertical distances (v)
  36218. var path1;
  36219. var path2;
  36220. var vertex1 = null;
  36221. var vertex2 = null;
  36222. for (i = 0; i < minlg + closePathCorr; i++) {
  36223. vTotalDistance[i] = 0;
  36224. vs[i] = [0];
  36225. for (p = 0; p < pathArray.length - 1; p++) {
  36226. path1 = pathArray[p];
  36227. path2 = pathArray[p + 1];
  36228. if (i === minlg) {
  36229. vertex1 = path1[0];
  36230. vertex2 = path2[0];
  36231. }
  36232. else {
  36233. vertex1 = path1[i];
  36234. vertex2 = path2[i];
  36235. }
  36236. vectlg = vertex2.subtract(vertex1).length();
  36237. dist = vectlg + vTotalDistance[i];
  36238. vs[i].push(dist);
  36239. vTotalDistance[i] = dist;
  36240. }
  36241. if (closeArray && vertex2 && vertex1) {
  36242. path1 = pathArray[p];
  36243. path2 = pathArray[0];
  36244. if (i === minlg) {
  36245. vertex2 = path2[0];
  36246. }
  36247. vectlg = vertex2.subtract(vertex1).length();
  36248. dist = vectlg + vTotalDistance[i];
  36249. vTotalDistance[i] = dist;
  36250. }
  36251. }
  36252. // uvs
  36253. var u;
  36254. var v;
  36255. if (customUV) {
  36256. for (p = 0; p < customUV.length; p++) {
  36257. uvs.push(customUV[p].x, customUV[p].y);
  36258. }
  36259. }
  36260. else {
  36261. for (p = 0; p < pathArray.length; p++) {
  36262. for (i = 0; i < minlg + closePathCorr; i++) {
  36263. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36264. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36265. if (invertUV) {
  36266. uvs.push(v, u);
  36267. }
  36268. else {
  36269. uvs.push(u, v);
  36270. }
  36271. }
  36272. }
  36273. }
  36274. // indices
  36275. p = 0; // path index
  36276. var pi = 0; // positions array index
  36277. var l1 = lg[p] - 1; // path1 length
  36278. var l2 = lg[p + 1] - 1; // path2 length
  36279. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36280. var shft = idx[1] - idx[0]; // shift
  36281. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36282. while (pi <= min && p < path1nb) {
  36283. // 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
  36284. indices.push(pi, pi + shft, pi + 1);
  36285. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36286. pi += 1;
  36287. if (pi === min) {
  36288. p++;
  36289. if (p === lg.length - 1) {
  36290. shft = idx[0] - idx[p];
  36291. l1 = lg[p] - 1;
  36292. l2 = lg[0] - 1;
  36293. }
  36294. else {
  36295. shft = idx[p + 1] - idx[p];
  36296. l1 = lg[p] - 1;
  36297. l2 = lg[p + 1] - 1;
  36298. }
  36299. pi = idx[p];
  36300. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36301. }
  36302. }
  36303. // normals
  36304. VertexData.ComputeNormals(positions, indices, normals);
  36305. if (closePath) {
  36306. var indexFirst = 0;
  36307. var indexLast = 0;
  36308. for (p = 0; p < pathArray.length; p++) {
  36309. indexFirst = idx[p] * 3;
  36310. if (p + 1 < pathArray.length) {
  36311. indexLast = (idx[p + 1] - 1) * 3;
  36312. }
  36313. else {
  36314. indexLast = normals.length - 3;
  36315. }
  36316. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36317. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36318. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36319. normals[indexLast] = normals[indexFirst];
  36320. normals[indexLast + 1] = normals[indexFirst + 1];
  36321. normals[indexLast + 2] = normals[indexFirst + 2];
  36322. }
  36323. }
  36324. // sides
  36325. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36326. // Colors
  36327. var colors = null;
  36328. if (customColors) {
  36329. colors = new Float32Array(customColors.length * 4);
  36330. for (var c = 0; c < customColors.length; c++) {
  36331. colors[c * 4] = customColors[c].r;
  36332. colors[c * 4 + 1] = customColors[c].g;
  36333. colors[c * 4 + 2] = customColors[c].b;
  36334. colors[c * 4 + 3] = customColors[c].a;
  36335. }
  36336. }
  36337. // Result
  36338. var vertexData = new VertexData();
  36339. var positions32 = new Float32Array(positions);
  36340. var normals32 = new Float32Array(normals);
  36341. var uvs32 = new Float32Array(uvs);
  36342. vertexData.indices = indices;
  36343. vertexData.positions = positions32;
  36344. vertexData.normals = normals32;
  36345. vertexData.uvs = uvs32;
  36346. if (colors) {
  36347. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36348. }
  36349. if (closePath) {
  36350. vertexData._idx = idx;
  36351. }
  36352. return vertexData;
  36353. };
  36354. /**
  36355. * Creates the VertexData for a box
  36356. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36357. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36358. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36359. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36360. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36361. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36362. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36363. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36364. * * 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)
  36365. * * 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)
  36366. * @returns the VertexData of the box
  36367. */
  36368. VertexData.CreateBox = function (options) {
  36369. var normalsSource = [
  36370. new BABYLON.Vector3(0, 0, 1),
  36371. new BABYLON.Vector3(0, 0, -1),
  36372. new BABYLON.Vector3(1, 0, 0),
  36373. new BABYLON.Vector3(-1, 0, 0),
  36374. new BABYLON.Vector3(0, 1, 0),
  36375. new BABYLON.Vector3(0, -1, 0)
  36376. ];
  36377. var indices = [];
  36378. var positions = [];
  36379. var normals = [];
  36380. var uvs = [];
  36381. var width = options.width || options.size || 1;
  36382. var height = options.height || options.size || 1;
  36383. var depth = options.depth || options.size || 1;
  36384. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36385. var faceUV = options.faceUV || new Array(6);
  36386. var faceColors = options.faceColors;
  36387. var colors = [];
  36388. // default face colors and UV if undefined
  36389. for (var f = 0; f < 6; f++) {
  36390. if (faceUV[f] === undefined) {
  36391. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36392. }
  36393. if (faceColors && faceColors[f] === undefined) {
  36394. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36395. }
  36396. }
  36397. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36398. // Create each face in turn.
  36399. for (var index = 0; index < normalsSource.length; index++) {
  36400. var normal = normalsSource[index];
  36401. // Get two vectors perpendicular to the face normal and to each other.
  36402. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36403. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36404. // Six indices (two triangles) per face.
  36405. var verticesLength = positions.length / 3;
  36406. indices.push(verticesLength);
  36407. indices.push(verticesLength + 1);
  36408. indices.push(verticesLength + 2);
  36409. indices.push(verticesLength);
  36410. indices.push(verticesLength + 2);
  36411. indices.push(verticesLength + 3);
  36412. // Four vertices per face.
  36413. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36414. positions.push(vertex.x, vertex.y, vertex.z);
  36415. normals.push(normal.x, normal.y, normal.z);
  36416. uvs.push(faceUV[index].z, faceUV[index].w);
  36417. if (faceColors) {
  36418. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36419. }
  36420. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36421. positions.push(vertex.x, vertex.y, vertex.z);
  36422. normals.push(normal.x, normal.y, normal.z);
  36423. uvs.push(faceUV[index].x, faceUV[index].w);
  36424. if (faceColors) {
  36425. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36426. }
  36427. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36428. positions.push(vertex.x, vertex.y, vertex.z);
  36429. normals.push(normal.x, normal.y, normal.z);
  36430. uvs.push(faceUV[index].x, faceUV[index].y);
  36431. if (faceColors) {
  36432. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36433. }
  36434. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36435. positions.push(vertex.x, vertex.y, vertex.z);
  36436. normals.push(normal.x, normal.y, normal.z);
  36437. uvs.push(faceUV[index].z, faceUV[index].y);
  36438. if (faceColors) {
  36439. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36440. }
  36441. }
  36442. // sides
  36443. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36444. // Result
  36445. var vertexData = new VertexData();
  36446. vertexData.indices = indices;
  36447. vertexData.positions = positions;
  36448. vertexData.normals = normals;
  36449. vertexData.uvs = uvs;
  36450. if (faceColors) {
  36451. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36452. vertexData.colors = totalColors;
  36453. }
  36454. return vertexData;
  36455. };
  36456. /**
  36457. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36458. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36459. * * segments sets the number of horizontal strips optional, default 32
  36460. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36461. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36462. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36463. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36464. * * 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
  36465. * * 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
  36466. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36467. * * 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)
  36468. * * 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)
  36469. * @returns the VertexData of the ellipsoid
  36470. */
  36471. VertexData.CreateSphere = function (options) {
  36472. var segments = options.segments || 32;
  36473. var diameterX = options.diameterX || options.diameter || 1;
  36474. var diameterY = options.diameterY || options.diameter || 1;
  36475. var diameterZ = options.diameterZ || options.diameter || 1;
  36476. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36477. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36478. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36479. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36480. var totalZRotationSteps = 2 + segments;
  36481. var totalYRotationSteps = 2 * totalZRotationSteps;
  36482. var indices = [];
  36483. var positions = [];
  36484. var normals = [];
  36485. var uvs = [];
  36486. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36487. var normalizedZ = zRotationStep / totalZRotationSteps;
  36488. var angleZ = normalizedZ * Math.PI * slice;
  36489. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36490. var normalizedY = yRotationStep / totalYRotationSteps;
  36491. var angleY = normalizedY * Math.PI * 2 * arc;
  36492. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36493. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36494. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36495. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36496. var vertex = complete.multiply(radius);
  36497. var normal = complete.divide(radius).normalize();
  36498. positions.push(vertex.x, vertex.y, vertex.z);
  36499. normals.push(normal.x, normal.y, normal.z);
  36500. uvs.push(normalizedY, normalizedZ);
  36501. }
  36502. if (zRotationStep > 0) {
  36503. var verticesCount = positions.length / 3;
  36504. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36505. indices.push((firstIndex));
  36506. indices.push((firstIndex + 1));
  36507. indices.push(firstIndex + totalYRotationSteps + 1);
  36508. indices.push((firstIndex + totalYRotationSteps + 1));
  36509. indices.push((firstIndex + 1));
  36510. indices.push((firstIndex + totalYRotationSteps + 2));
  36511. }
  36512. }
  36513. }
  36514. // Sides
  36515. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36516. // Result
  36517. var vertexData = new VertexData();
  36518. vertexData.indices = indices;
  36519. vertexData.positions = positions;
  36520. vertexData.normals = normals;
  36521. vertexData.uvs = uvs;
  36522. return vertexData;
  36523. };
  36524. /**
  36525. * Creates the VertexData for a cylinder, cone or prism
  36526. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36527. * * height sets the height (y direction) of the cylinder, optional, default 2
  36528. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36529. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36530. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36531. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36532. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36533. * * 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
  36534. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36535. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36536. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36537. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36538. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36539. * * 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)
  36540. * * 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)
  36541. * @returns the VertexData of the cylinder, cone or prism
  36542. */
  36543. VertexData.CreateCylinder = function (options) {
  36544. var height = options.height || 2;
  36545. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36546. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36547. var tessellation = options.tessellation || 24;
  36548. var subdivisions = options.subdivisions || 1;
  36549. var hasRings = options.hasRings ? true : false;
  36550. var enclose = options.enclose ? true : false;
  36551. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36552. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36553. var faceUV = options.faceUV || new Array(3);
  36554. var faceColors = options.faceColors;
  36555. // default face colors and UV if undefined
  36556. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36557. var ringNb = (hasRings) ? subdivisions : 1;
  36558. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36559. var f;
  36560. for (f = 0; f < surfaceNb; f++) {
  36561. if (faceColors && faceColors[f] === undefined) {
  36562. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36563. }
  36564. }
  36565. for (f = 0; f < surfaceNb; f++) {
  36566. if (faceUV && faceUV[f] === undefined) {
  36567. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36568. }
  36569. }
  36570. var indices = new Array();
  36571. var positions = new Array();
  36572. var normals = new Array();
  36573. var uvs = new Array();
  36574. var colors = new Array();
  36575. var angle_step = Math.PI * 2 * arc / tessellation;
  36576. var angle;
  36577. var h;
  36578. var radius;
  36579. var tan = (diameterBottom - diameterTop) / 2 / height;
  36580. var ringVertex = BABYLON.Vector3.Zero();
  36581. var ringNormal = BABYLON.Vector3.Zero();
  36582. var ringFirstVertex = BABYLON.Vector3.Zero();
  36583. var ringFirstNormal = BABYLON.Vector3.Zero();
  36584. var quadNormal = BABYLON.Vector3.Zero();
  36585. var Y = BABYLON.Axis.Y;
  36586. // positions, normals, uvs
  36587. var i;
  36588. var j;
  36589. var r;
  36590. var ringIdx = 1;
  36591. var s = 1; // surface index
  36592. var cs = 0;
  36593. var v = 0;
  36594. for (i = 0; i <= subdivisions; i++) {
  36595. h = i / subdivisions;
  36596. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36597. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36598. for (r = 0; r < ringIdx; r++) {
  36599. if (hasRings) {
  36600. s += r;
  36601. }
  36602. if (enclose) {
  36603. s += 2 * r;
  36604. }
  36605. for (j = 0; j <= tessellation; j++) {
  36606. angle = j * angle_step;
  36607. // position
  36608. ringVertex.x = Math.cos(-angle) * radius;
  36609. ringVertex.y = -height / 2 + h * height;
  36610. ringVertex.z = Math.sin(-angle) * radius;
  36611. // normal
  36612. if (diameterTop === 0 && i === subdivisions) {
  36613. // if no top cap, reuse former normals
  36614. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36615. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36616. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36617. }
  36618. else {
  36619. ringNormal.x = ringVertex.x;
  36620. ringNormal.z = ringVertex.z;
  36621. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36622. ringNormal.normalize();
  36623. }
  36624. // keep first ring vertex values for enclose
  36625. if (j === 0) {
  36626. ringFirstVertex.copyFrom(ringVertex);
  36627. ringFirstNormal.copyFrom(ringNormal);
  36628. }
  36629. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36630. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36631. if (hasRings) {
  36632. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36633. }
  36634. else {
  36635. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36636. }
  36637. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36638. if (faceColors) {
  36639. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36640. }
  36641. }
  36642. // if enclose, add four vertices and their dedicated normals
  36643. if (arc !== 1 && enclose) {
  36644. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36645. positions.push(0, ringVertex.y, 0);
  36646. positions.push(0, ringVertex.y, 0);
  36647. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36648. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36649. quadNormal.normalize();
  36650. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36651. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36652. quadNormal.normalize();
  36653. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36654. if (hasRings) {
  36655. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36656. }
  36657. else {
  36658. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36659. }
  36660. uvs.push(faceUV[s + 1].x, v);
  36661. uvs.push(faceUV[s + 1].z, v);
  36662. if (hasRings) {
  36663. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36664. }
  36665. else {
  36666. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36667. }
  36668. uvs.push(faceUV[s + 2].x, v);
  36669. uvs.push(faceUV[s + 2].z, v);
  36670. if (faceColors) {
  36671. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36672. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36673. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36674. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36675. }
  36676. }
  36677. if (cs !== s) {
  36678. cs = s;
  36679. }
  36680. }
  36681. }
  36682. // indices
  36683. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36684. var s;
  36685. i = 0;
  36686. for (s = 0; s < subdivisions; s++) {
  36687. var i0 = 0;
  36688. var i1 = 0;
  36689. var i2 = 0;
  36690. var i3 = 0;
  36691. for (j = 0; j < tessellation; j++) {
  36692. i0 = i * (e + 1) + j;
  36693. i1 = (i + 1) * (e + 1) + j;
  36694. i2 = i * (e + 1) + (j + 1);
  36695. i3 = (i + 1) * (e + 1) + (j + 1);
  36696. indices.push(i0, i1, i2);
  36697. indices.push(i3, i2, i1);
  36698. }
  36699. if (arc !== 1 && enclose) {
  36700. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36701. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36702. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36703. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36704. }
  36705. i = (hasRings) ? (i + 2) : (i + 1);
  36706. }
  36707. // Caps
  36708. var createCylinderCap = function (isTop) {
  36709. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36710. if (radius === 0) {
  36711. return;
  36712. }
  36713. // Cap positions, normals & uvs
  36714. var angle;
  36715. var circleVector;
  36716. var i;
  36717. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36718. var c = null;
  36719. if (faceColors) {
  36720. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36721. }
  36722. // cap center
  36723. var vbase = positions.length / 3;
  36724. var offset = isTop ? height / 2 : -height / 2;
  36725. var center = new BABYLON.Vector3(0, offset, 0);
  36726. positions.push(center.x, center.y, center.z);
  36727. normals.push(0, isTop ? 1 : -1, 0);
  36728. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36729. if (c) {
  36730. colors.push(c.r, c.g, c.b, c.a);
  36731. }
  36732. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36733. for (i = 0; i <= tessellation; i++) {
  36734. angle = Math.PI * 2 * i * arc / tessellation;
  36735. var cos = Math.cos(-angle);
  36736. var sin = Math.sin(-angle);
  36737. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36738. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36739. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36740. normals.push(0, isTop ? 1 : -1, 0);
  36741. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36742. if (c) {
  36743. colors.push(c.r, c.g, c.b, c.a);
  36744. }
  36745. }
  36746. // Cap indices
  36747. for (i = 0; i < tessellation; i++) {
  36748. if (!isTop) {
  36749. indices.push(vbase);
  36750. indices.push(vbase + (i + 1));
  36751. indices.push(vbase + (i + 2));
  36752. }
  36753. else {
  36754. indices.push(vbase);
  36755. indices.push(vbase + (i + 2));
  36756. indices.push(vbase + (i + 1));
  36757. }
  36758. }
  36759. };
  36760. // add caps to geometry
  36761. createCylinderCap(false);
  36762. createCylinderCap(true);
  36763. // Sides
  36764. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36765. var vertexData = new VertexData();
  36766. vertexData.indices = indices;
  36767. vertexData.positions = positions;
  36768. vertexData.normals = normals;
  36769. vertexData.uvs = uvs;
  36770. if (faceColors) {
  36771. vertexData.colors = colors;
  36772. }
  36773. return vertexData;
  36774. };
  36775. /**
  36776. * Creates the VertexData for a torus
  36777. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36778. * * diameter the diameter of the torus, optional default 1
  36779. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36780. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36781. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36782. * * 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)
  36783. * * 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)
  36784. * @returns the VertexData of the torus
  36785. */
  36786. VertexData.CreateTorus = function (options) {
  36787. var indices = [];
  36788. var positions = [];
  36789. var normals = [];
  36790. var uvs = [];
  36791. var diameter = options.diameter || 1;
  36792. var thickness = options.thickness || 0.5;
  36793. var tessellation = options.tessellation || 16;
  36794. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36795. var stride = tessellation + 1;
  36796. for (var i = 0; i <= tessellation; i++) {
  36797. var u = i / tessellation;
  36798. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36799. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36800. for (var j = 0; j <= tessellation; j++) {
  36801. var v = 1 - j / tessellation;
  36802. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36803. var dx = Math.cos(innerAngle);
  36804. var dy = Math.sin(innerAngle);
  36805. // Create a vertex.
  36806. var normal = new BABYLON.Vector3(dx, dy, 0);
  36807. var position = normal.scale(thickness / 2);
  36808. var textureCoordinate = new BABYLON.Vector2(u, v);
  36809. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36810. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36811. positions.push(position.x, position.y, position.z);
  36812. normals.push(normal.x, normal.y, normal.z);
  36813. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36814. // And create indices for two triangles.
  36815. var nextI = (i + 1) % stride;
  36816. var nextJ = (j + 1) % stride;
  36817. indices.push(i * stride + j);
  36818. indices.push(i * stride + nextJ);
  36819. indices.push(nextI * stride + j);
  36820. indices.push(i * stride + nextJ);
  36821. indices.push(nextI * stride + nextJ);
  36822. indices.push(nextI * stride + j);
  36823. }
  36824. }
  36825. // Sides
  36826. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36827. // Result
  36828. var vertexData = new VertexData();
  36829. vertexData.indices = indices;
  36830. vertexData.positions = positions;
  36831. vertexData.normals = normals;
  36832. vertexData.uvs = uvs;
  36833. return vertexData;
  36834. };
  36835. /**
  36836. * Creates the VertexData of the LineSystem
  36837. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36838. * - lines an array of lines, each line being an array of successive Vector3
  36839. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36840. * @returns the VertexData of the LineSystem
  36841. */
  36842. VertexData.CreateLineSystem = function (options) {
  36843. var indices = [];
  36844. var positions = [];
  36845. var lines = options.lines;
  36846. var colors = options.colors;
  36847. var vertexColors = [];
  36848. var idx = 0;
  36849. for (var l = 0; l < lines.length; l++) {
  36850. var points = lines[l];
  36851. for (var index = 0; index < points.length; index++) {
  36852. positions.push(points[index].x, points[index].y, points[index].z);
  36853. if (colors) {
  36854. var color = colors[l];
  36855. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36856. }
  36857. if (index > 0) {
  36858. indices.push(idx - 1);
  36859. indices.push(idx);
  36860. }
  36861. idx++;
  36862. }
  36863. }
  36864. var vertexData = new VertexData();
  36865. vertexData.indices = indices;
  36866. vertexData.positions = positions;
  36867. if (colors) {
  36868. vertexData.colors = vertexColors;
  36869. }
  36870. return vertexData;
  36871. };
  36872. /**
  36873. * Create the VertexData for a DashedLines
  36874. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36875. * - points an array successive Vector3
  36876. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36877. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36878. * - dashNb the intended total number of dashes, optional, default 200
  36879. * @returns the VertexData for the DashedLines
  36880. */
  36881. VertexData.CreateDashedLines = function (options) {
  36882. var dashSize = options.dashSize || 3;
  36883. var gapSize = options.gapSize || 1;
  36884. var dashNb = options.dashNb || 200;
  36885. var points = options.points;
  36886. var positions = new Array();
  36887. var indices = new Array();
  36888. var curvect = BABYLON.Vector3.Zero();
  36889. var lg = 0;
  36890. var nb = 0;
  36891. var shft = 0;
  36892. var dashshft = 0;
  36893. var curshft = 0;
  36894. var idx = 0;
  36895. var i = 0;
  36896. for (i = 0; i < points.length - 1; i++) {
  36897. points[i + 1].subtractToRef(points[i], curvect);
  36898. lg += curvect.length();
  36899. }
  36900. shft = lg / dashNb;
  36901. dashshft = dashSize * shft / (dashSize + gapSize);
  36902. for (i = 0; i < points.length - 1; i++) {
  36903. points[i + 1].subtractToRef(points[i], curvect);
  36904. nb = Math.floor(curvect.length() / shft);
  36905. curvect.normalize();
  36906. for (var j = 0; j < nb; j++) {
  36907. curshft = shft * j;
  36908. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36909. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36910. indices.push(idx, idx + 1);
  36911. idx += 2;
  36912. }
  36913. }
  36914. // Result
  36915. var vertexData = new VertexData();
  36916. vertexData.positions = positions;
  36917. vertexData.indices = indices;
  36918. return vertexData;
  36919. };
  36920. /**
  36921. * Creates the VertexData for a Ground
  36922. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36923. * - width the width (x direction) of the ground, optional, default 1
  36924. * - height the height (z direction) of the ground, optional, default 1
  36925. * - subdivisions the number of subdivisions per side, optional, default 1
  36926. * @returns the VertexData of the Ground
  36927. */
  36928. VertexData.CreateGround = function (options) {
  36929. var indices = [];
  36930. var positions = [];
  36931. var normals = [];
  36932. var uvs = [];
  36933. var row, col;
  36934. var width = options.width || 1;
  36935. var height = options.height || 1;
  36936. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36937. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36938. for (row = 0; row <= subdivisionsY; row++) {
  36939. for (col = 0; col <= subdivisionsX; col++) {
  36940. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36941. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36942. positions.push(position.x, position.y, position.z);
  36943. normals.push(normal.x, normal.y, normal.z);
  36944. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36945. }
  36946. }
  36947. for (row = 0; row < subdivisionsY; row++) {
  36948. for (col = 0; col < subdivisionsX; col++) {
  36949. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36950. indices.push(col + 1 + row * (subdivisionsX + 1));
  36951. indices.push(col + row * (subdivisionsX + 1));
  36952. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36953. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36954. indices.push(col + row * (subdivisionsX + 1));
  36955. }
  36956. }
  36957. // Result
  36958. var vertexData = new VertexData();
  36959. vertexData.indices = indices;
  36960. vertexData.positions = positions;
  36961. vertexData.normals = normals;
  36962. vertexData.uvs = uvs;
  36963. return vertexData;
  36964. };
  36965. /**
  36966. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  36967. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36968. * * xmin the ground minimum X coordinate, optional, default -1
  36969. * * zmin the ground minimum Z coordinate, optional, default -1
  36970. * * xmax the ground maximum X coordinate, optional, default 1
  36971. * * zmax the ground maximum Z coordinate, optional, default 1
  36972. * * 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}
  36973. * * 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}
  36974. * @returns the VertexData of the TiledGround
  36975. */
  36976. VertexData.CreateTiledGround = function (options) {
  36977. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36978. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36979. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36980. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36981. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36982. var precision = options.precision || { w: 1, h: 1 };
  36983. var indices = new Array();
  36984. var positions = new Array();
  36985. var normals = new Array();
  36986. var uvs = new Array();
  36987. var row, col, tileRow, tileCol;
  36988. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36989. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36990. precision.w = (precision.w < 1) ? 1 : precision.w;
  36991. precision.h = (precision.h < 1) ? 1 : precision.h;
  36992. var tileSize = {
  36993. 'w': (xmax - xmin) / subdivisions.w,
  36994. 'h': (zmax - zmin) / subdivisions.h
  36995. };
  36996. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36997. // Indices
  36998. var base = positions.length / 3;
  36999. var rowLength = precision.w + 1;
  37000. for (row = 0; row < precision.h; row++) {
  37001. for (col = 0; col < precision.w; col++) {
  37002. var square = [
  37003. base + col + row * rowLength,
  37004. base + (col + 1) + row * rowLength,
  37005. base + (col + 1) + (row + 1) * rowLength,
  37006. base + col + (row + 1) * rowLength
  37007. ];
  37008. indices.push(square[1]);
  37009. indices.push(square[2]);
  37010. indices.push(square[3]);
  37011. indices.push(square[0]);
  37012. indices.push(square[1]);
  37013. indices.push(square[3]);
  37014. }
  37015. }
  37016. // Position, normals and uvs
  37017. var position = BABYLON.Vector3.Zero();
  37018. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37019. for (row = 0; row <= precision.h; row++) {
  37020. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37021. for (col = 0; col <= precision.w; col++) {
  37022. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37023. position.y = 0;
  37024. positions.push(position.x, position.y, position.z);
  37025. normals.push(normal.x, normal.y, normal.z);
  37026. uvs.push(col / precision.w, row / precision.h);
  37027. }
  37028. }
  37029. }
  37030. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37031. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37032. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37033. }
  37034. }
  37035. // Result
  37036. var vertexData = new VertexData();
  37037. vertexData.indices = indices;
  37038. vertexData.positions = positions;
  37039. vertexData.normals = normals;
  37040. vertexData.uvs = uvs;
  37041. return vertexData;
  37042. };
  37043. /**
  37044. * Creates the VertexData of the Ground designed from a heightmap
  37045. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37046. * * width the width (x direction) of the ground
  37047. * * height the height (z direction) of the ground
  37048. * * subdivisions the number of subdivisions per side
  37049. * * minHeight the minimum altitude on the ground, optional, default 0
  37050. * * maxHeight the maximum altitude on the ground, optional default 1
  37051. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37052. * * buffer the array holding the image color data
  37053. * * bufferWidth the width of image
  37054. * * bufferHeight the height of image
  37055. * @returns the VertexData of the Ground designed from a heightmap
  37056. */
  37057. VertexData.CreateGroundFromHeightMap = function (options) {
  37058. var indices = [];
  37059. var positions = [];
  37060. var normals = [];
  37061. var uvs = [];
  37062. var row, col;
  37063. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37064. // Vertices
  37065. for (row = 0; row <= options.subdivisions; row++) {
  37066. for (col = 0; col <= options.subdivisions; col++) {
  37067. 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));
  37068. // Compute height
  37069. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37070. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37071. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37072. var r = options.buffer[pos] / 255.0;
  37073. var g = options.buffer[pos + 1] / 255.0;
  37074. var b = options.buffer[pos + 2] / 255.0;
  37075. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37076. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37077. // Add vertex
  37078. positions.push(position.x, position.y, position.z);
  37079. normals.push(0, 0, 0);
  37080. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37081. }
  37082. }
  37083. // Indices
  37084. for (row = 0; row < options.subdivisions; row++) {
  37085. for (col = 0; col < options.subdivisions; col++) {
  37086. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37087. indices.push(col + 1 + row * (options.subdivisions + 1));
  37088. indices.push(col + row * (options.subdivisions + 1));
  37089. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37090. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37091. indices.push(col + row * (options.subdivisions + 1));
  37092. }
  37093. }
  37094. // Normals
  37095. VertexData.ComputeNormals(positions, indices, normals);
  37096. // Result
  37097. var vertexData = new VertexData();
  37098. vertexData.indices = indices;
  37099. vertexData.positions = positions;
  37100. vertexData.normals = normals;
  37101. vertexData.uvs = uvs;
  37102. return vertexData;
  37103. };
  37104. /**
  37105. * Creates the VertexData for a Plane
  37106. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37107. * * size sets the width and height of the plane to the value of size, optional default 1
  37108. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37109. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37110. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37111. * * 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)
  37112. * * 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)
  37113. * @returns the VertexData of the box
  37114. */
  37115. VertexData.CreatePlane = function (options) {
  37116. var indices = [];
  37117. var positions = [];
  37118. var normals = [];
  37119. var uvs = [];
  37120. var width = options.width || options.size || 1;
  37121. var height = options.height || options.size || 1;
  37122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37123. // Vertices
  37124. var halfWidth = width / 2.0;
  37125. var halfHeight = height / 2.0;
  37126. positions.push(-halfWidth, -halfHeight, 0);
  37127. normals.push(0, 0, -1.0);
  37128. uvs.push(0.0, 0.0);
  37129. positions.push(halfWidth, -halfHeight, 0);
  37130. normals.push(0, 0, -1.0);
  37131. uvs.push(1.0, 0.0);
  37132. positions.push(halfWidth, halfHeight, 0);
  37133. normals.push(0, 0, -1.0);
  37134. uvs.push(1.0, 1.0);
  37135. positions.push(-halfWidth, halfHeight, 0);
  37136. normals.push(0, 0, -1.0);
  37137. uvs.push(0.0, 1.0);
  37138. // Indices
  37139. indices.push(0);
  37140. indices.push(1);
  37141. indices.push(2);
  37142. indices.push(0);
  37143. indices.push(2);
  37144. indices.push(3);
  37145. // Sides
  37146. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37147. // Result
  37148. var vertexData = new VertexData();
  37149. vertexData.indices = indices;
  37150. vertexData.positions = positions;
  37151. vertexData.normals = normals;
  37152. vertexData.uvs = uvs;
  37153. return vertexData;
  37154. };
  37155. /**
  37156. * Creates the VertexData of the Disc or regular Polygon
  37157. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37158. * * radius the radius of the disc, optional default 0.5
  37159. * * tessellation the number of polygon sides, optional, default 64
  37160. * * 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
  37161. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37162. * * 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)
  37163. * * 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)
  37164. * @returns the VertexData of the box
  37165. */
  37166. VertexData.CreateDisc = function (options) {
  37167. var positions = new Array();
  37168. var indices = new Array();
  37169. var normals = new Array();
  37170. var uvs = new Array();
  37171. var radius = options.radius || 0.5;
  37172. var tessellation = options.tessellation || 64;
  37173. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37174. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37175. // positions and uvs
  37176. positions.push(0, 0, 0); // disc center first
  37177. uvs.push(0.5, 0.5);
  37178. var theta = Math.PI * 2 * arc;
  37179. var step = theta / tessellation;
  37180. for (var a = 0; a < theta; a += step) {
  37181. var x = Math.cos(a);
  37182. var y = Math.sin(a);
  37183. var u = (x + 1) / 2;
  37184. var v = (1 - y) / 2;
  37185. positions.push(radius * x, radius * y, 0);
  37186. uvs.push(u, v);
  37187. }
  37188. if (arc === 1) {
  37189. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37190. uvs.push(uvs[2], uvs[3]);
  37191. }
  37192. //indices
  37193. var vertexNb = positions.length / 3;
  37194. for (var i = 1; i < vertexNb - 1; i++) {
  37195. indices.push(i + 1, 0, i);
  37196. }
  37197. // result
  37198. VertexData.ComputeNormals(positions, indices, normals);
  37199. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37200. var vertexData = new VertexData();
  37201. vertexData.indices = indices;
  37202. vertexData.positions = positions;
  37203. vertexData.normals = normals;
  37204. vertexData.uvs = uvs;
  37205. return vertexData;
  37206. };
  37207. /**
  37208. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37209. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37210. * @param polygon a mesh built from polygonTriangulation.build()
  37211. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37212. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37213. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37214. * @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)
  37215. * @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)
  37216. * @returns the VertexData of the Polygon
  37217. */
  37218. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37219. var faceUV = fUV || new Array(3);
  37220. var faceColors = fColors;
  37221. var colors = [];
  37222. // default face colors and UV if undefined
  37223. for (var f = 0; f < 3; f++) {
  37224. if (faceUV[f] === undefined) {
  37225. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37226. }
  37227. if (faceColors && faceColors[f] === undefined) {
  37228. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37229. }
  37230. }
  37231. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37232. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37233. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37234. var indices = polygon.getIndices();
  37235. // set face colours and textures
  37236. var idx = 0;
  37237. var face = 0;
  37238. for (var index = 0; index < normals.length; index += 3) {
  37239. //Edge Face no. 1
  37240. if (Math.abs(normals[index + 1]) < 0.001) {
  37241. face = 1;
  37242. }
  37243. //Top Face no. 0
  37244. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37245. face = 0;
  37246. }
  37247. //Bottom Face no. 2
  37248. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37249. face = 2;
  37250. }
  37251. idx = index / 3;
  37252. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37253. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37254. if (faceColors) {
  37255. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37256. }
  37257. }
  37258. // sides
  37259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37260. // Result
  37261. var vertexData = new VertexData();
  37262. vertexData.indices = indices;
  37263. vertexData.positions = positions;
  37264. vertexData.normals = normals;
  37265. vertexData.uvs = uvs;
  37266. if (faceColors) {
  37267. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37268. vertexData.colors = totalColors;
  37269. }
  37270. return vertexData;
  37271. };
  37272. /**
  37273. * Creates the VertexData of the IcoSphere
  37274. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37275. * * radius the radius of the IcoSphere, optional default 1
  37276. * * radiusX allows stretching in the x direction, optional, default radius
  37277. * * radiusY allows stretching in the y direction, optional, default radius
  37278. * * radiusZ allows stretching in the z direction, optional, default radius
  37279. * * flat when true creates a flat shaded mesh, optional, default true
  37280. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37281. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37282. * * 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)
  37283. * * 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)
  37284. * @returns the VertexData of the IcoSphere
  37285. */
  37286. VertexData.CreateIcoSphere = function (options) {
  37287. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37288. var radius = options.radius || 1;
  37289. var flat = (options.flat === undefined) ? true : options.flat;
  37290. var subdivisions = options.subdivisions || 4;
  37291. var radiusX = options.radiusX || radius;
  37292. var radiusY = options.radiusY || radius;
  37293. var radiusZ = options.radiusZ || radius;
  37294. var t = (1 + Math.sqrt(5)) / 2;
  37295. // 12 vertex x,y,z
  37296. var ico_vertices = [
  37297. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37298. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37299. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37300. ];
  37301. // index of 3 vertex makes a face of icopshere
  37302. var ico_indices = [
  37303. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37304. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37305. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37306. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37307. ];
  37308. // vertex for uv have aliased position, not for UV
  37309. var vertices_unalias_id = [
  37310. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37311. // vertex alias
  37312. 0,
  37313. 2,
  37314. 3,
  37315. 3,
  37316. 3,
  37317. 4,
  37318. 7,
  37319. 8,
  37320. 9,
  37321. 9,
  37322. 10,
  37323. 11 // 23: B + 12
  37324. ];
  37325. // uv as integer step (not pixels !)
  37326. var ico_vertexuv = [
  37327. 5, 1, 3, 1, 6, 4, 0, 0,
  37328. 5, 3, 4, 2, 2, 2, 4, 0,
  37329. 2, 0, 1, 1, 6, 0, 6, 2,
  37330. // vertex alias (for same vertex on different faces)
  37331. 0, 4,
  37332. 3, 3,
  37333. 4, 4,
  37334. 3, 1,
  37335. 4, 2,
  37336. 4, 4,
  37337. 0, 2,
  37338. 1, 1,
  37339. 2, 2,
  37340. 3, 3,
  37341. 1, 3,
  37342. 2, 4 // 23: B + 12
  37343. ];
  37344. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37345. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37346. // First island of uv mapping
  37347. // v = 4h 3+ 2
  37348. // v = 3h 9+ 4
  37349. // v = 2h 9+ 5 B
  37350. // v = 1h 9 1 0
  37351. // v = 0h 3 8 7 A
  37352. // u = 0 1 2 3 4 5 6 *a
  37353. // Second island of uv mapping
  37354. // v = 4h 0+ B+ 4+
  37355. // v = 3h A+ 2+
  37356. // v = 2h 7+ 6 3+
  37357. // v = 1h 8+ 3+
  37358. // v = 0h
  37359. // u = 0 1 2 3 4 5 6 *a
  37360. // Face layout on texture UV mapping
  37361. // ============
  37362. // \ 4 /\ 16 / ======
  37363. // \ / \ / /\ 11 /
  37364. // \/ 7 \/ / \ /
  37365. // ======= / 10 \/
  37366. // /\ 17 /\ =======
  37367. // / \ / \ \ 15 /\
  37368. // / 8 \/ 12 \ \ / \
  37369. // ============ \/ 6 \
  37370. // \ 18 /\ ============
  37371. // \ / \ \ 5 /\ 0 /
  37372. // \/ 13 \ \ / \ /
  37373. // ======= \/ 1 \/
  37374. // =============
  37375. // /\ 19 /\ 2 /\
  37376. // / \ / \ / \
  37377. // / 14 \/ 9 \/ 3 \
  37378. // ===================
  37379. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37380. var ustep = 138 / 1024;
  37381. var vstep = 239 / 1024;
  37382. var uoffset = 60 / 1024;
  37383. var voffset = 26 / 1024;
  37384. // Second island should have margin, not to touch the first island
  37385. // avoid any borderline artefact in pixel rounding
  37386. var island_u_offset = -40 / 1024;
  37387. var island_v_offset = +20 / 1024;
  37388. // face is either island 0 or 1 :
  37389. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37390. var island = [
  37391. 0, 0, 0, 0, 1,
  37392. 0, 0, 1, 1, 0,
  37393. 0, 0, 1, 1, 0,
  37394. 0, 1, 1, 1, 0 // 15 - 19
  37395. ];
  37396. var indices = new Array();
  37397. var positions = new Array();
  37398. var normals = new Array();
  37399. var uvs = new Array();
  37400. var current_indice = 0;
  37401. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37402. var face_vertex_pos = new Array(3);
  37403. var face_vertex_uv = new Array(3);
  37404. var v012;
  37405. for (v012 = 0; v012 < 3; v012++) {
  37406. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37407. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37408. }
  37409. // create all with normals
  37410. for (var face = 0; face < 20; face++) {
  37411. // 3 vertex per face
  37412. for (v012 = 0; v012 < 3; v012++) {
  37413. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37414. var v_id = ico_indices[3 * face + v012];
  37415. // vertex have 3D position (x,y,z)
  37416. 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]);
  37417. // Normalize to get normal, then scale to radius
  37418. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37419. // uv Coordinates from vertex ID
  37420. 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);
  37421. }
  37422. // Subdivide the face (interpolate pos, norm, uv)
  37423. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37424. // - norm is linear interpolation of vertex corner normal
  37425. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37426. // - uv is linear interpolation
  37427. //
  37428. // Topology is as below for sub-divide by 2
  37429. // vertex shown as v0,v1,v2
  37430. // interp index is i1 to progress in range [v0,v1[
  37431. // interp index is i2 to progress in range [v0,v2[
  37432. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37433. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37434. //
  37435. //
  37436. // i2 v2
  37437. // ^ ^
  37438. // / / \
  37439. // / / \
  37440. // / / \
  37441. // / / (0,1) \
  37442. // / #---------\
  37443. // / / \ (0,0)'/ \
  37444. // / / \ / \
  37445. // / / \ / \
  37446. // / / (0,0) \ / (1,0) \
  37447. // / #---------#---------\
  37448. // v0 v1
  37449. //
  37450. // --------------------> i1
  37451. //
  37452. // interp of (i1,i2):
  37453. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37454. // along i1 : lerp(x0,x1, i1/(S-i2))
  37455. //
  37456. // centroid of triangle is needed to get help normal computation
  37457. // (c1,c2) are used for centroid location
  37458. var interp_vertex = function (i1, i2, c1, c2) {
  37459. // vertex is interpolated from
  37460. // - face_vertex_pos[0..2]
  37461. // - face_vertex_uv[0..2]
  37462. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37463. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37464. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37465. pos_interp.normalize();
  37466. var vertex_normal;
  37467. if (flat) {
  37468. // in flat mode, recalculate normal as face centroid normal
  37469. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37470. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37471. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37472. }
  37473. else {
  37474. // in smooth mode, recalculate normal from each single vertex position
  37475. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37476. }
  37477. // Vertex normal need correction due to X,Y,Z radius scaling
  37478. vertex_normal.x /= radiusX;
  37479. vertex_normal.y /= radiusY;
  37480. vertex_normal.z /= radiusZ;
  37481. vertex_normal.normalize();
  37482. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37483. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37484. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37485. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37486. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37487. uvs.push(uv_interp.x, uv_interp.y);
  37488. // push each vertex has member of a face
  37489. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37490. indices.push(current_indice);
  37491. current_indice++;
  37492. };
  37493. for (var i2 = 0; i2 < subdivisions; i2++) {
  37494. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37495. // face : (i1,i2) for /\ :
  37496. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37497. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37498. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37499. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37500. if (i1 + i2 + 1 < subdivisions) {
  37501. // face : (i1,i2)' for \/ :
  37502. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37503. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37504. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37505. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37506. }
  37507. }
  37508. }
  37509. }
  37510. // Sides
  37511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37512. // Result
  37513. var vertexData = new VertexData();
  37514. vertexData.indices = indices;
  37515. vertexData.positions = positions;
  37516. vertexData.normals = normals;
  37517. vertexData.uvs = uvs;
  37518. return vertexData;
  37519. };
  37520. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37521. /**
  37522. * Creates the VertexData for a Polyhedron
  37523. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37524. * * type provided types are:
  37525. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37526. * * 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)
  37527. * * size the size of the IcoSphere, optional default 1
  37528. * * sizeX allows stretching in the x direction, optional, default size
  37529. * * sizeY allows stretching in the y direction, optional, default size
  37530. * * sizeZ allows stretching in the z direction, optional, default size
  37531. * * 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
  37532. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37533. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37534. * * flat when true creates a flat shaded mesh, optional, default true
  37535. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37536. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37537. * * 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)
  37538. * * 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)
  37539. * @returns the VertexData of the Polyhedron
  37540. */
  37541. VertexData.CreatePolyhedron = function (options) {
  37542. // provided polyhedron types :
  37543. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37544. // 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)
  37545. var polyhedra = [];
  37546. 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]] };
  37547. 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]] };
  37548. polyhedra[2] = {
  37549. 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]],
  37550. 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]]
  37551. };
  37552. polyhedra[3] = {
  37553. 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]],
  37554. 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]]
  37555. };
  37556. polyhedra[4] = {
  37557. 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]],
  37558. 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]]
  37559. };
  37560. 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]] };
  37561. 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]] };
  37562. 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]] };
  37563. 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]] };
  37564. 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]] };
  37565. 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]] };
  37566. 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]] };
  37567. 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]] };
  37568. 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]] };
  37569. polyhedra[14] = {
  37570. 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]],
  37571. 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]]
  37572. };
  37573. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37574. var size = options.size;
  37575. var sizeX = options.sizeX || size || 1;
  37576. var sizeY = options.sizeY || size || 1;
  37577. var sizeZ = options.sizeZ || size || 1;
  37578. var data = options.custom || polyhedra[type];
  37579. var nbfaces = data.face.length;
  37580. var faceUV = options.faceUV || new Array(nbfaces);
  37581. var faceColors = options.faceColors;
  37582. var flat = (options.flat === undefined) ? true : options.flat;
  37583. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37584. var positions = new Array();
  37585. var indices = new Array();
  37586. var normals = new Array();
  37587. var uvs = new Array();
  37588. var colors = new Array();
  37589. var index = 0;
  37590. var faceIdx = 0; // face cursor in the array "indexes"
  37591. var indexes = new Array();
  37592. var i = 0;
  37593. var f = 0;
  37594. var u, v, ang, x, y, tmp;
  37595. // default face colors and UV if undefined
  37596. if (flat) {
  37597. for (f = 0; f < nbfaces; f++) {
  37598. if (faceColors && faceColors[f] === undefined) {
  37599. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37600. }
  37601. if (faceUV && faceUV[f] === undefined) {
  37602. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37603. }
  37604. }
  37605. }
  37606. if (!flat) {
  37607. for (i = 0; i < data.vertex.length; i++) {
  37608. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37609. uvs.push(0, 0);
  37610. }
  37611. for (f = 0; f < nbfaces; f++) {
  37612. for (i = 0; i < data.face[f].length - 2; i++) {
  37613. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37614. }
  37615. }
  37616. }
  37617. else {
  37618. for (f = 0; f < nbfaces; f++) {
  37619. var fl = data.face[f].length; // number of vertices of the current face
  37620. ang = 2 * Math.PI / fl;
  37621. x = 0.5 * Math.tan(ang / 2);
  37622. y = 0.5;
  37623. // positions, uvs, colors
  37624. for (i = 0; i < fl; i++) {
  37625. // positions
  37626. 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);
  37627. indexes.push(index);
  37628. index++;
  37629. // uvs
  37630. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37631. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37632. uvs.push(u, v);
  37633. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37634. y = x * Math.sin(ang) + y * Math.cos(ang);
  37635. x = tmp;
  37636. // colors
  37637. if (faceColors) {
  37638. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37639. }
  37640. }
  37641. // indices from indexes
  37642. for (i = 0; i < fl - 2; i++) {
  37643. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37644. }
  37645. faceIdx += fl;
  37646. }
  37647. }
  37648. VertexData.ComputeNormals(positions, indices, normals);
  37649. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37650. var vertexData = new VertexData();
  37651. vertexData.positions = positions;
  37652. vertexData.indices = indices;
  37653. vertexData.normals = normals;
  37654. vertexData.uvs = uvs;
  37655. if (faceColors && flat) {
  37656. vertexData.colors = colors;
  37657. }
  37658. return vertexData;
  37659. };
  37660. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37661. /**
  37662. * Creates the VertexData for a TorusKnot
  37663. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37664. * * radius the radius of the torus knot, optional, default 2
  37665. * * tube the thickness of the tube, optional, default 0.5
  37666. * * radialSegments the number of sides on each tube segments, optional, default 32
  37667. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37668. * * p the number of windings around the z axis, optional, default 2
  37669. * * q the number of windings around the x axis, optional, default 3
  37670. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37671. * * 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)
  37672. * * 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)
  37673. * @returns the VertexData of the Torus Knot
  37674. */
  37675. VertexData.CreateTorusKnot = function (options) {
  37676. var indices = new Array();
  37677. var positions = new Array();
  37678. var normals = new Array();
  37679. var uvs = new Array();
  37680. var radius = options.radius || 2;
  37681. var tube = options.tube || 0.5;
  37682. var radialSegments = options.radialSegments || 32;
  37683. var tubularSegments = options.tubularSegments || 32;
  37684. var p = options.p || 2;
  37685. var q = options.q || 3;
  37686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37687. // Helper
  37688. var getPos = function (angle) {
  37689. var cu = Math.cos(angle);
  37690. var su = Math.sin(angle);
  37691. var quOverP = q / p * angle;
  37692. var cs = Math.cos(quOverP);
  37693. var tx = radius * (2 + cs) * 0.5 * cu;
  37694. var ty = radius * (2 + cs) * su * 0.5;
  37695. var tz = radius * Math.sin(quOverP) * 0.5;
  37696. return new BABYLON.Vector3(tx, ty, tz);
  37697. };
  37698. // Vertices
  37699. var i;
  37700. var j;
  37701. for (i = 0; i <= radialSegments; i++) {
  37702. var modI = i % radialSegments;
  37703. var u = modI / radialSegments * 2 * p * Math.PI;
  37704. var p1 = getPos(u);
  37705. var p2 = getPos(u + 0.01);
  37706. var tang = p2.subtract(p1);
  37707. var n = p2.add(p1);
  37708. var bitan = BABYLON.Vector3.Cross(tang, n);
  37709. n = BABYLON.Vector3.Cross(bitan, tang);
  37710. bitan.normalize();
  37711. n.normalize();
  37712. for (j = 0; j < tubularSegments; j++) {
  37713. var modJ = j % tubularSegments;
  37714. var v = modJ / tubularSegments * 2 * Math.PI;
  37715. var cx = -tube * Math.cos(v);
  37716. var cy = tube * Math.sin(v);
  37717. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37718. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37719. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37720. uvs.push(i / radialSegments);
  37721. uvs.push(j / tubularSegments);
  37722. }
  37723. }
  37724. for (i = 0; i < radialSegments; i++) {
  37725. for (j = 0; j < tubularSegments; j++) {
  37726. var jNext = (j + 1) % tubularSegments;
  37727. var a = i * tubularSegments + j;
  37728. var b = (i + 1) * tubularSegments + j;
  37729. var c = (i + 1) * tubularSegments + jNext;
  37730. var d = i * tubularSegments + jNext;
  37731. indices.push(d);
  37732. indices.push(b);
  37733. indices.push(a);
  37734. indices.push(d);
  37735. indices.push(c);
  37736. indices.push(b);
  37737. }
  37738. }
  37739. // Normals
  37740. VertexData.ComputeNormals(positions, indices, normals);
  37741. // Sides
  37742. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37743. // Result
  37744. var vertexData = new VertexData();
  37745. vertexData.indices = indices;
  37746. vertexData.positions = positions;
  37747. vertexData.normals = normals;
  37748. vertexData.uvs = uvs;
  37749. return vertexData;
  37750. };
  37751. // Tools
  37752. /**
  37753. * Compute normals for given positions and indices
  37754. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37755. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37756. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37757. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37758. * * facetNormals : optional array of facet normals (vector3)
  37759. * * facetPositions : optional array of facet positions (vector3)
  37760. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37761. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37762. * * bInfo : optional bounding info, required for facetPartitioning computation
  37763. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37764. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37765. * * useRightHandedSystem: optional boolean to for right handed system computation
  37766. * * depthSort : optional boolean to enable the facet depth sort computation
  37767. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37768. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37769. */
  37770. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37771. // temporary scalar variables
  37772. var index = 0; // facet index
  37773. var p1p2x = 0.0; // p1p2 vector x coordinate
  37774. var p1p2y = 0.0; // p1p2 vector y coordinate
  37775. var p1p2z = 0.0; // p1p2 vector z coordinate
  37776. var p3p2x = 0.0; // p3p2 vector x coordinate
  37777. var p3p2y = 0.0; // p3p2 vector y coordinate
  37778. var p3p2z = 0.0; // p3p2 vector z coordinate
  37779. var faceNormalx = 0.0; // facet normal x coordinate
  37780. var faceNormaly = 0.0; // facet normal y coordinate
  37781. var faceNormalz = 0.0; // facet normal z coordinate
  37782. var length = 0.0; // facet normal length before normalization
  37783. var v1x = 0; // vector1 x index in the positions array
  37784. var v1y = 0; // vector1 y index in the positions array
  37785. var v1z = 0; // vector1 z index in the positions array
  37786. var v2x = 0; // vector2 x index in the positions array
  37787. var v2y = 0; // vector2 y index in the positions array
  37788. var v2z = 0; // vector2 z index in the positions array
  37789. var v3x = 0; // vector3 x index in the positions array
  37790. var v3y = 0; // vector3 y index in the positions array
  37791. var v3z = 0; // vector3 z index in the positions array
  37792. var computeFacetNormals = false;
  37793. var computeFacetPositions = false;
  37794. var computeFacetPartitioning = false;
  37795. var computeDepthSort = false;
  37796. var faceNormalSign = 1;
  37797. var ratio = 0;
  37798. var distanceTo = null;
  37799. if (options) {
  37800. computeFacetNormals = (options.facetNormals) ? true : false;
  37801. computeFacetPositions = (options.facetPositions) ? true : false;
  37802. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37803. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37804. ratio = options.ratio || 0;
  37805. computeDepthSort = (options.depthSort) ? true : false;
  37806. distanceTo = (options.distanceTo);
  37807. if (computeDepthSort) {
  37808. if (distanceTo === undefined) {
  37809. distanceTo = BABYLON.Vector3.Zero();
  37810. }
  37811. var depthSortedFacets = options.depthSortedFacets;
  37812. }
  37813. }
  37814. // facetPartitioning reinit if needed
  37815. var xSubRatio = 0;
  37816. var ySubRatio = 0;
  37817. var zSubRatio = 0;
  37818. var subSq = 0;
  37819. if (computeFacetPartitioning && options && options.bbSize) {
  37820. var ox = 0; // X partitioning index for facet position
  37821. var oy = 0; // Y partinioning index for facet position
  37822. var oz = 0; // Z partinioning index for facet position
  37823. var b1x = 0; // X partitioning index for facet v1 vertex
  37824. var b1y = 0; // Y partitioning index for facet v1 vertex
  37825. var b1z = 0; // z partitioning index for facet v1 vertex
  37826. var b2x = 0; // X partitioning index for facet v2 vertex
  37827. var b2y = 0; // Y partitioning index for facet v2 vertex
  37828. var b2z = 0; // Z partitioning index for facet v2 vertex
  37829. var b3x = 0; // X partitioning index for facet v3 vertex
  37830. var b3y = 0; // Y partitioning index for facet v3 vertex
  37831. var b3z = 0; // Z partitioning index for facet v3 vertex
  37832. var block_idx_o = 0; // facet barycenter block index
  37833. var block_idx_v1 = 0; // v1 vertex block index
  37834. var block_idx_v2 = 0; // v2 vertex block index
  37835. var block_idx_v3 = 0; // v3 vertex block index
  37836. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37837. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37838. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37839. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37840. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37841. subSq = options.subDiv.max * options.subDiv.max;
  37842. options.facetPartitioning.length = 0;
  37843. }
  37844. // reset the normals
  37845. for (index = 0; index < positions.length; index++) {
  37846. normals[index] = 0.0;
  37847. }
  37848. // Loop : 1 indice triplet = 1 facet
  37849. var nbFaces = (indices.length / 3) | 0;
  37850. for (index = 0; index < nbFaces; index++) {
  37851. // get the indexes of the coordinates of each vertex of the facet
  37852. v1x = indices[index * 3] * 3;
  37853. v1y = v1x + 1;
  37854. v1z = v1x + 2;
  37855. v2x = indices[index * 3 + 1] * 3;
  37856. v2y = v2x + 1;
  37857. v2z = v2x + 2;
  37858. v3x = indices[index * 3 + 2] * 3;
  37859. v3y = v3x + 1;
  37860. v3z = v3x + 2;
  37861. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37862. p1p2y = positions[v1y] - positions[v2y];
  37863. p1p2z = positions[v1z] - positions[v2z];
  37864. p3p2x = positions[v3x] - positions[v2x];
  37865. p3p2y = positions[v3y] - positions[v2y];
  37866. p3p2z = positions[v3z] - positions[v2z];
  37867. // compute the face normal with the cross product
  37868. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37869. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37870. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37871. // normalize this normal and store it in the array facetData
  37872. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37873. length = (length === 0) ? 1.0 : length;
  37874. faceNormalx /= length;
  37875. faceNormaly /= length;
  37876. faceNormalz /= length;
  37877. if (computeFacetNormals && options) {
  37878. options.facetNormals[index].x = faceNormalx;
  37879. options.facetNormals[index].y = faceNormaly;
  37880. options.facetNormals[index].z = faceNormalz;
  37881. }
  37882. if (computeFacetPositions && options) {
  37883. // compute and the facet barycenter coordinates in the array facetPositions
  37884. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37885. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37886. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37887. }
  37888. if (computeFacetPartitioning && options) {
  37889. // store the facet indexes in arrays in the main facetPartitioning array :
  37890. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37891. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37892. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37893. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37894. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37895. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37896. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37897. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37898. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37899. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37900. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37901. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37902. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37903. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37904. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37905. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37906. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37907. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37908. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37909. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37910. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37911. // push each facet index in each block containing the vertex
  37912. options.facetPartitioning[block_idx_v1].push(index);
  37913. if (block_idx_v2 != block_idx_v1) {
  37914. options.facetPartitioning[block_idx_v2].push(index);
  37915. }
  37916. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37917. options.facetPartitioning[block_idx_v3].push(index);
  37918. }
  37919. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37920. options.facetPartitioning[block_idx_o].push(index);
  37921. }
  37922. }
  37923. if (computeDepthSort && options && options.facetPositions) {
  37924. var dsf = depthSortedFacets[index];
  37925. dsf.ind = index * 3;
  37926. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37927. }
  37928. // compute the normals anyway
  37929. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37930. normals[v1y] += faceNormaly;
  37931. normals[v1z] += faceNormalz;
  37932. normals[v2x] += faceNormalx;
  37933. normals[v2y] += faceNormaly;
  37934. normals[v2z] += faceNormalz;
  37935. normals[v3x] += faceNormalx;
  37936. normals[v3y] += faceNormaly;
  37937. normals[v3z] += faceNormalz;
  37938. }
  37939. // last normalization of each normal
  37940. for (index = 0; index < normals.length / 3; index++) {
  37941. faceNormalx = normals[index * 3];
  37942. faceNormaly = normals[index * 3 + 1];
  37943. faceNormalz = normals[index * 3 + 2];
  37944. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37945. length = (length === 0) ? 1.0 : length;
  37946. faceNormalx /= length;
  37947. faceNormaly /= length;
  37948. faceNormalz /= length;
  37949. normals[index * 3] = faceNormalx;
  37950. normals[index * 3 + 1] = faceNormaly;
  37951. normals[index * 3 + 2] = faceNormalz;
  37952. }
  37953. };
  37954. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37955. var li = indices.length;
  37956. var ln = normals.length;
  37957. var i;
  37958. var n;
  37959. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37960. switch (sideOrientation) {
  37961. case BABYLON.Mesh.FRONTSIDE:
  37962. // nothing changed
  37963. break;
  37964. case BABYLON.Mesh.BACKSIDE:
  37965. var tmp;
  37966. // indices
  37967. for (i = 0; i < li; i += 3) {
  37968. tmp = indices[i];
  37969. indices[i] = indices[i + 2];
  37970. indices[i + 2] = tmp;
  37971. }
  37972. // normals
  37973. for (n = 0; n < ln; n++) {
  37974. normals[n] = -normals[n];
  37975. }
  37976. break;
  37977. case BABYLON.Mesh.DOUBLESIDE:
  37978. // positions
  37979. var lp = positions.length;
  37980. var l = lp / 3;
  37981. for (var p = 0; p < lp; p++) {
  37982. positions[lp + p] = positions[p];
  37983. }
  37984. // indices
  37985. for (i = 0; i < li; i += 3) {
  37986. indices[i + li] = indices[i + 2] + l;
  37987. indices[i + 1 + li] = indices[i + 1] + l;
  37988. indices[i + 2 + li] = indices[i] + l;
  37989. }
  37990. // normals
  37991. for (n = 0; n < ln; n++) {
  37992. normals[ln + n] = -normals[n];
  37993. }
  37994. // uvs
  37995. var lu = uvs.length;
  37996. var u = 0;
  37997. for (u = 0; u < lu; u++) {
  37998. uvs[u + lu] = uvs[u];
  37999. }
  38000. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38001. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38002. u = 0;
  38003. for (i = 0; i < lu / 2; i++) {
  38004. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38005. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38006. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38007. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38008. u += 2;
  38009. }
  38010. break;
  38011. }
  38012. };
  38013. /**
  38014. * Applies VertexData created from the imported parameters to the geometry
  38015. * @param parsedVertexData the parsed data from an imported file
  38016. * @param geometry the geometry to apply the VertexData to
  38017. */
  38018. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38019. var vertexData = new VertexData();
  38020. // positions
  38021. var positions = parsedVertexData.positions;
  38022. if (positions) {
  38023. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38024. }
  38025. // normals
  38026. var normals = parsedVertexData.normals;
  38027. if (normals) {
  38028. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38029. }
  38030. // tangents
  38031. var tangents = parsedVertexData.tangents;
  38032. if (tangents) {
  38033. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38034. }
  38035. // uvs
  38036. var uvs = parsedVertexData.uvs;
  38037. if (uvs) {
  38038. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38039. }
  38040. // uv2s
  38041. var uv2s = parsedVertexData.uv2s;
  38042. if (uv2s) {
  38043. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38044. }
  38045. // uv3s
  38046. var uv3s = parsedVertexData.uv3s;
  38047. if (uv3s) {
  38048. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38049. }
  38050. // uv4s
  38051. var uv4s = parsedVertexData.uv4s;
  38052. if (uv4s) {
  38053. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38054. }
  38055. // uv5s
  38056. var uv5s = parsedVertexData.uv5s;
  38057. if (uv5s) {
  38058. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38059. }
  38060. // uv6s
  38061. var uv6s = parsedVertexData.uv6s;
  38062. if (uv6s) {
  38063. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38064. }
  38065. // colors
  38066. var colors = parsedVertexData.colors;
  38067. if (colors) {
  38068. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38069. }
  38070. // matricesIndices
  38071. var matricesIndices = parsedVertexData.matricesIndices;
  38072. if (matricesIndices) {
  38073. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38074. }
  38075. // matricesWeights
  38076. var matricesWeights = parsedVertexData.matricesWeights;
  38077. if (matricesWeights) {
  38078. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38079. }
  38080. // indices
  38081. var indices = parsedVertexData.indices;
  38082. if (indices) {
  38083. vertexData.indices = indices;
  38084. }
  38085. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38086. };
  38087. return VertexData;
  38088. }());
  38089. BABYLON.VertexData = VertexData;
  38090. })(BABYLON || (BABYLON = {}));
  38091. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38092. "use strict";
  38093. var BABYLON;
  38094. (function (BABYLON) {
  38095. /**
  38096. * Class used to store geometry data (vertex buffers + index buffer)
  38097. */
  38098. var Geometry = /** @class */ (function () {
  38099. /**
  38100. * Creates a new geometry
  38101. * @param id defines the unique ID
  38102. * @param scene defines the hosting scene
  38103. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38104. * @param updatable defines if geometry must be updatable (false by default)
  38105. * @param mesh defines the mesh that will be associated with the geometry
  38106. */
  38107. function Geometry(id, scene, vertexData, updatable, mesh) {
  38108. if (updatable === void 0) { updatable = false; }
  38109. if (mesh === void 0) { mesh = null; }
  38110. /**
  38111. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38112. */
  38113. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38114. this._totalVertices = 0;
  38115. this._isDisposed = false;
  38116. this._indexBufferIsUpdatable = false;
  38117. this.id = id;
  38118. this._engine = scene.getEngine();
  38119. this._meshes = [];
  38120. this._scene = scene;
  38121. //Init vertex buffer cache
  38122. this._vertexBuffers = {};
  38123. this._indices = [];
  38124. this._updatable = updatable;
  38125. // vertexData
  38126. if (vertexData) {
  38127. this.setAllVerticesData(vertexData, updatable);
  38128. }
  38129. else {
  38130. this._totalVertices = 0;
  38131. this._indices = [];
  38132. }
  38133. if (this._engine.getCaps().vertexArrayObject) {
  38134. this._vertexArrayObjects = {};
  38135. }
  38136. // applyToMesh
  38137. if (mesh) {
  38138. if (mesh.getClassName() === "LinesMesh") {
  38139. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38140. this._updateExtend();
  38141. }
  38142. this.applyToMesh(mesh);
  38143. mesh.computeWorldMatrix(true);
  38144. }
  38145. }
  38146. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38147. /**
  38148. * 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
  38149. */
  38150. get: function () {
  38151. return this._boundingBias;
  38152. },
  38153. /**
  38154. * 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
  38155. */
  38156. set: function (value) {
  38157. if (this._boundingBias && this._boundingBias.equals(value)) {
  38158. return;
  38159. }
  38160. this._boundingBias = value.clone();
  38161. this._updateBoundingInfo(true, null);
  38162. },
  38163. enumerable: true,
  38164. configurable: true
  38165. });
  38166. /**
  38167. * Static function used to attach a new empty geometry to a mesh
  38168. * @param mesh defines the mesh to attach the geometry to
  38169. * @returns the new {BABYLON.Geometry}
  38170. */
  38171. Geometry.CreateGeometryForMesh = function (mesh) {
  38172. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38173. geometry.applyToMesh(mesh);
  38174. return geometry;
  38175. };
  38176. Object.defineProperty(Geometry.prototype, "extend", {
  38177. /**
  38178. * Gets the current extend of the geometry
  38179. */
  38180. get: function () {
  38181. return this._extend;
  38182. },
  38183. enumerable: true,
  38184. configurable: true
  38185. });
  38186. /**
  38187. * Gets the hosting scene
  38188. * @returns the hosting {BABYLON.Scene}
  38189. */
  38190. Geometry.prototype.getScene = function () {
  38191. return this._scene;
  38192. };
  38193. /**
  38194. * Gets the hosting engine
  38195. * @returns the hosting {BABYLON.Engine}
  38196. */
  38197. Geometry.prototype.getEngine = function () {
  38198. return this._engine;
  38199. };
  38200. /**
  38201. * Defines if the geometry is ready to use
  38202. * @returns true if the geometry is ready to be used
  38203. */
  38204. Geometry.prototype.isReady = function () {
  38205. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38206. };
  38207. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38208. /**
  38209. * Gets a value indicating that the geometry should not be serialized
  38210. */
  38211. get: function () {
  38212. for (var index = 0; index < this._meshes.length; index++) {
  38213. if (!this._meshes[index].doNotSerialize) {
  38214. return false;
  38215. }
  38216. }
  38217. return true;
  38218. },
  38219. enumerable: true,
  38220. configurable: true
  38221. });
  38222. /** @ignore */
  38223. Geometry.prototype._rebuild = function () {
  38224. if (this._vertexArrayObjects) {
  38225. this._vertexArrayObjects = {};
  38226. }
  38227. // Index buffer
  38228. if (this._meshes.length !== 0 && this._indices) {
  38229. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38230. }
  38231. // Vertex buffers
  38232. for (var key in this._vertexBuffers) {
  38233. var vertexBuffer = this._vertexBuffers[key];
  38234. vertexBuffer._rebuild();
  38235. }
  38236. };
  38237. /**
  38238. * Affects all gemetry data in one call
  38239. * @param vertexData defines the geometry data
  38240. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38241. */
  38242. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38243. vertexData.applyToGeometry(this, updatable);
  38244. this.notifyUpdate();
  38245. };
  38246. /**
  38247. * Set specific vertex data
  38248. * @param kind defines the data kind (Position, normal, etc...)
  38249. * @param data defines the vertex data to use
  38250. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38251. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38252. */
  38253. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38254. if (updatable === void 0) { updatable = false; }
  38255. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38256. this.setVerticesBuffer(buffer);
  38257. };
  38258. /**
  38259. * Removes a specific vertex data
  38260. * @param kind defines the data kind (Position, normal, etc...)
  38261. */
  38262. Geometry.prototype.removeVerticesData = function (kind) {
  38263. if (this._vertexBuffers[kind]) {
  38264. this._vertexBuffers[kind].dispose();
  38265. delete this._vertexBuffers[kind];
  38266. }
  38267. };
  38268. /**
  38269. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38270. * @param buffer defines the vertex buffer to use
  38271. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38272. */
  38273. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38274. if (totalVertices === void 0) { totalVertices = null; }
  38275. var kind = buffer.getKind();
  38276. if (this._vertexBuffers[kind]) {
  38277. this._vertexBuffers[kind].dispose();
  38278. }
  38279. this._vertexBuffers[kind] = buffer;
  38280. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38281. var data = buffer.getData();
  38282. if (totalVertices != null) {
  38283. this._totalVertices = totalVertices;
  38284. }
  38285. else {
  38286. if (data != null) {
  38287. this._totalVertices = data.length / (buffer.byteStride / 4);
  38288. }
  38289. }
  38290. this._updateExtend(data);
  38291. this._resetPointsArrayCache();
  38292. var meshes = this._meshes;
  38293. var numOfMeshes = meshes.length;
  38294. for (var index = 0; index < numOfMeshes; index++) {
  38295. var mesh = meshes[index];
  38296. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38297. mesh._createGlobalSubMesh(false);
  38298. mesh.computeWorldMatrix(true);
  38299. }
  38300. }
  38301. this.notifyUpdate(kind);
  38302. if (this._vertexArrayObjects) {
  38303. this._disposeVertexArrayObjects();
  38304. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38305. }
  38306. };
  38307. /**
  38308. * Update a specific vertex buffer
  38309. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38310. * It will do nothing if the buffer is not updatable
  38311. * @param kind defines the data kind (Position, normal, etc...)
  38312. * @param data defines the data to use
  38313. * @param offset defines the offset in the target buffer where to store the data
  38314. * @param useBytes set to true if the offset is in bytes
  38315. */
  38316. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38317. if (useBytes === void 0) { useBytes = false; }
  38318. var vertexBuffer = this.getVertexBuffer(kind);
  38319. if (!vertexBuffer) {
  38320. return;
  38321. }
  38322. vertexBuffer.updateDirectly(data, offset, useBytes);
  38323. this.notifyUpdate(kind);
  38324. };
  38325. /**
  38326. * Update a specific vertex buffer
  38327. * This function will create a new buffer if the current one is not updatable
  38328. * @param kind defines the data kind (Position, normal, etc...)
  38329. * @param data defines the data to use
  38330. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38331. */
  38332. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38333. if (updateExtends === void 0) { updateExtends = false; }
  38334. var vertexBuffer = this.getVertexBuffer(kind);
  38335. if (!vertexBuffer) {
  38336. return;
  38337. }
  38338. vertexBuffer.update(data);
  38339. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38340. this._updateBoundingInfo(updateExtends, data);
  38341. }
  38342. this.notifyUpdate(kind);
  38343. };
  38344. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38345. if (updateExtends) {
  38346. this._updateExtend(data);
  38347. }
  38348. var meshes = this._meshes;
  38349. var numOfMeshes = meshes.length;
  38350. this._resetPointsArrayCache();
  38351. for (var index = 0; index < numOfMeshes; index++) {
  38352. var mesh = meshes[index];
  38353. if (updateExtends) {
  38354. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38355. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38356. var subMesh = mesh.subMeshes[subIndex];
  38357. subMesh.refreshBoundingInfo();
  38358. }
  38359. }
  38360. }
  38361. };
  38362. /** @ignore */
  38363. Geometry.prototype._bind = function (effect, indexToBind) {
  38364. if (!effect) {
  38365. return;
  38366. }
  38367. if (indexToBind === undefined) {
  38368. indexToBind = this._indexBuffer;
  38369. }
  38370. var vbs = this.getVertexBuffers();
  38371. if (!vbs) {
  38372. return;
  38373. }
  38374. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38375. this._engine.bindBuffers(vbs, indexToBind, effect);
  38376. return;
  38377. }
  38378. // Using VAO
  38379. if (!this._vertexArrayObjects[effect.key]) {
  38380. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38381. }
  38382. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38383. };
  38384. /**
  38385. * Gets total number of vertices
  38386. * @returns the total number of vertices
  38387. */
  38388. Geometry.prototype.getTotalVertices = function () {
  38389. if (!this.isReady()) {
  38390. return 0;
  38391. }
  38392. return this._totalVertices;
  38393. };
  38394. /**
  38395. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38396. * @param kind defines the data kind (Position, normal, etc...)
  38397. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38398. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38399. * @returns a float array containing vertex data
  38400. */
  38401. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38402. var vertexBuffer = this.getVertexBuffer(kind);
  38403. if (!vertexBuffer) {
  38404. return null;
  38405. }
  38406. var data = vertexBuffer.getData();
  38407. if (!data) {
  38408. return null;
  38409. }
  38410. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38411. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38412. var count = this._totalVertices * defaultStride;
  38413. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38414. var copy_1 = new Array(count);
  38415. vertexBuffer.forEach(count, function (value, index) {
  38416. copy_1[index] = value;
  38417. });
  38418. return copy_1;
  38419. }
  38420. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38421. if (data instanceof Array) {
  38422. var offset = vertexBuffer.byteOffset / 4;
  38423. return BABYLON.Tools.Slice(data, offset, offset + count);
  38424. }
  38425. else if (data instanceof ArrayBuffer) {
  38426. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38427. }
  38428. else {
  38429. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38430. }
  38431. }
  38432. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38433. return BABYLON.Tools.Slice(data);
  38434. }
  38435. return data;
  38436. };
  38437. /**
  38438. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38439. * @param kind defines the data kind (Position, normal, etc...)
  38440. * @returns true if the vertex buffer with the specified kind is updatable
  38441. */
  38442. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38443. var vb = this._vertexBuffers[kind];
  38444. if (!vb) {
  38445. return false;
  38446. }
  38447. return vb.isUpdatable();
  38448. };
  38449. /**
  38450. * Gets a specific vertex buffer
  38451. * @param kind defines the data kind (Position, normal, etc...)
  38452. * @returns a {BABYLON.VertexBuffer}
  38453. */
  38454. Geometry.prototype.getVertexBuffer = function (kind) {
  38455. if (!this.isReady()) {
  38456. return null;
  38457. }
  38458. return this._vertexBuffers[kind];
  38459. };
  38460. /**
  38461. * Returns all vertex buffers
  38462. * @return an object holding all vertex buffers indexed by kind
  38463. */
  38464. Geometry.prototype.getVertexBuffers = function () {
  38465. if (!this.isReady()) {
  38466. return null;
  38467. }
  38468. return this._vertexBuffers;
  38469. };
  38470. /**
  38471. * Gets a boolean indicating if specific vertex buffer is present
  38472. * @param kind defines the data kind (Position, normal, etc...)
  38473. * @returns true if data is present
  38474. */
  38475. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38476. if (!this._vertexBuffers) {
  38477. if (this._delayInfo) {
  38478. return this._delayInfo.indexOf(kind) !== -1;
  38479. }
  38480. return false;
  38481. }
  38482. return this._vertexBuffers[kind] !== undefined;
  38483. };
  38484. /**
  38485. * Gets a list of all attached data kinds (Position, normal, etc...)
  38486. * @returns a list of string containing all kinds
  38487. */
  38488. Geometry.prototype.getVerticesDataKinds = function () {
  38489. var result = [];
  38490. var kind;
  38491. if (!this._vertexBuffers && this._delayInfo) {
  38492. for (kind in this._delayInfo) {
  38493. result.push(kind);
  38494. }
  38495. }
  38496. else {
  38497. for (kind in this._vertexBuffers) {
  38498. result.push(kind);
  38499. }
  38500. }
  38501. return result;
  38502. };
  38503. /**
  38504. * Update index buffer
  38505. * @param indices defines the indices to store in the index buffer
  38506. * @param offset defines the offset in the target buffer where to store the data
  38507. */
  38508. Geometry.prototype.updateIndices = function (indices, offset) {
  38509. if (!this._indexBuffer) {
  38510. return;
  38511. }
  38512. if (!this._indexBufferIsUpdatable) {
  38513. this.setIndices(indices, null, true);
  38514. }
  38515. else {
  38516. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38517. }
  38518. };
  38519. /**
  38520. * Creates a new index buffer
  38521. * @param indices defines the indices to store in the index buffer
  38522. * @param totalVertices defines the total number of vertices (could be null)
  38523. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38524. */
  38525. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38526. if (totalVertices === void 0) { totalVertices = null; }
  38527. if (updatable === void 0) { updatable = false; }
  38528. if (this._indexBuffer) {
  38529. this._engine._releaseBuffer(this._indexBuffer);
  38530. }
  38531. this._disposeVertexArrayObjects();
  38532. this._indices = indices;
  38533. this._indexBufferIsUpdatable = updatable;
  38534. if (this._meshes.length !== 0 && this._indices) {
  38535. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38536. }
  38537. if (totalVertices != undefined) {
  38538. this._totalVertices = totalVertices;
  38539. }
  38540. var meshes = this._meshes;
  38541. var numOfMeshes = meshes.length;
  38542. for (var index = 0; index < numOfMeshes; index++) {
  38543. meshes[index]._createGlobalSubMesh(true);
  38544. }
  38545. this.notifyUpdate();
  38546. };
  38547. /**
  38548. * Return the total number of indices
  38549. * @returns the total number of indices
  38550. */
  38551. Geometry.prototype.getTotalIndices = function () {
  38552. if (!this.isReady()) {
  38553. return 0;
  38554. }
  38555. return this._indices.length;
  38556. };
  38557. /**
  38558. * Gets the index buffer array
  38559. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38560. * @returns the index buffer array
  38561. */
  38562. Geometry.prototype.getIndices = function (copyWhenShared) {
  38563. if (!this.isReady()) {
  38564. return null;
  38565. }
  38566. var orig = this._indices;
  38567. if (!copyWhenShared || this._meshes.length === 1) {
  38568. return orig;
  38569. }
  38570. else {
  38571. var len = orig.length;
  38572. var copy = [];
  38573. for (var i = 0; i < len; i++) {
  38574. copy.push(orig[i]);
  38575. }
  38576. return copy;
  38577. }
  38578. };
  38579. /**
  38580. * Gets the index buffer
  38581. * @return the index buffer
  38582. */
  38583. Geometry.prototype.getIndexBuffer = function () {
  38584. if (!this.isReady()) {
  38585. return null;
  38586. }
  38587. return this._indexBuffer;
  38588. };
  38589. /** @ignore */
  38590. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38591. if (effect === void 0) { effect = null; }
  38592. if (!effect || !this._vertexArrayObjects) {
  38593. return;
  38594. }
  38595. if (this._vertexArrayObjects[effect.key]) {
  38596. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38597. delete this._vertexArrayObjects[effect.key];
  38598. }
  38599. };
  38600. /**
  38601. * Release the associated resources for a specific mesh
  38602. * @param mesh defines the source mesh
  38603. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38604. */
  38605. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38606. var meshes = this._meshes;
  38607. var index = meshes.indexOf(mesh);
  38608. if (index === -1) {
  38609. return;
  38610. }
  38611. meshes.splice(index, 1);
  38612. mesh._geometry = null;
  38613. if (meshes.length === 0 && shouldDispose) {
  38614. this.dispose();
  38615. }
  38616. };
  38617. /**
  38618. * Apply current geometry to a given mesh
  38619. * @param mesh defines the mesh to apply geometry to
  38620. */
  38621. Geometry.prototype.applyToMesh = function (mesh) {
  38622. if (mesh._geometry === this) {
  38623. return;
  38624. }
  38625. var previousGeometry = mesh._geometry;
  38626. if (previousGeometry) {
  38627. previousGeometry.releaseForMesh(mesh);
  38628. }
  38629. var meshes = this._meshes;
  38630. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38631. mesh._geometry = this;
  38632. this._scene.pushGeometry(this);
  38633. meshes.push(mesh);
  38634. if (this.isReady()) {
  38635. this._applyToMesh(mesh);
  38636. }
  38637. else {
  38638. mesh._boundingInfo = this._boundingInfo;
  38639. }
  38640. };
  38641. Geometry.prototype._updateExtend = function (data) {
  38642. if (data === void 0) { data = null; }
  38643. if (!data) {
  38644. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38645. }
  38646. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38647. };
  38648. Geometry.prototype._applyToMesh = function (mesh) {
  38649. var numOfMeshes = this._meshes.length;
  38650. // vertexBuffers
  38651. for (var kind in this._vertexBuffers) {
  38652. if (numOfMeshes === 1) {
  38653. this._vertexBuffers[kind].create();
  38654. }
  38655. var buffer = this._vertexBuffers[kind].getBuffer();
  38656. if (buffer)
  38657. buffer.references = numOfMeshes;
  38658. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38659. if (!this._extend) {
  38660. this._updateExtend();
  38661. }
  38662. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38663. mesh._createGlobalSubMesh(false);
  38664. //bounding info was just created again, world matrix should be applied again.
  38665. mesh._updateBoundingInfo();
  38666. }
  38667. }
  38668. // indexBuffer
  38669. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38670. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38671. }
  38672. if (this._indexBuffer) {
  38673. this._indexBuffer.references = numOfMeshes;
  38674. }
  38675. };
  38676. Geometry.prototype.notifyUpdate = function (kind) {
  38677. if (this.onGeometryUpdated) {
  38678. this.onGeometryUpdated(this, kind);
  38679. }
  38680. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38681. var mesh = _a[_i];
  38682. mesh._markSubMeshesAsAttributesDirty();
  38683. }
  38684. };
  38685. /**
  38686. * Load the geometry if it was flagged as delay loaded
  38687. * @param scene defines the hosting scene
  38688. * @param onLoaded defines a callback called when the geometry is loaded
  38689. */
  38690. Geometry.prototype.load = function (scene, onLoaded) {
  38691. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38692. return;
  38693. }
  38694. if (this.isReady()) {
  38695. if (onLoaded) {
  38696. onLoaded();
  38697. }
  38698. return;
  38699. }
  38700. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38701. this._queueLoad(scene, onLoaded);
  38702. };
  38703. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38704. var _this = this;
  38705. if (!this.delayLoadingFile) {
  38706. return;
  38707. }
  38708. scene._addPendingData(this);
  38709. scene._loadFile(this.delayLoadingFile, function (data) {
  38710. if (!_this._delayLoadingFunction) {
  38711. return;
  38712. }
  38713. _this._delayLoadingFunction(JSON.parse(data), _this);
  38714. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38715. _this._delayInfo = [];
  38716. scene._removePendingData(_this);
  38717. var meshes = _this._meshes;
  38718. var numOfMeshes = meshes.length;
  38719. for (var index = 0; index < numOfMeshes; index++) {
  38720. _this._applyToMesh(meshes[index]);
  38721. }
  38722. if (onLoaded) {
  38723. onLoaded();
  38724. }
  38725. }, undefined, true);
  38726. };
  38727. /**
  38728. * Invert the geometry to move from a right handed system to a left handed one.
  38729. */
  38730. Geometry.prototype.toLeftHanded = function () {
  38731. // Flip faces
  38732. var tIndices = this.getIndices(false);
  38733. if (tIndices != null && tIndices.length > 0) {
  38734. for (var i = 0; i < tIndices.length; i += 3) {
  38735. var tTemp = tIndices[i + 0];
  38736. tIndices[i + 0] = tIndices[i + 2];
  38737. tIndices[i + 2] = tTemp;
  38738. }
  38739. this.setIndices(tIndices);
  38740. }
  38741. // Negate position.z
  38742. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38743. if (tPositions != null && tPositions.length > 0) {
  38744. for (var i = 0; i < tPositions.length; i += 3) {
  38745. tPositions[i + 2] = -tPositions[i + 2];
  38746. }
  38747. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38748. }
  38749. // Negate normal.z
  38750. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38751. if (tNormals != null && tNormals.length > 0) {
  38752. for (var i = 0; i < tNormals.length; i += 3) {
  38753. tNormals[i + 2] = -tNormals[i + 2];
  38754. }
  38755. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38756. }
  38757. };
  38758. // Cache
  38759. /** @ignore */
  38760. Geometry.prototype._resetPointsArrayCache = function () {
  38761. this._positions = null;
  38762. };
  38763. /** @ignore */
  38764. Geometry.prototype._generatePointsArray = function () {
  38765. if (this._positions)
  38766. return true;
  38767. this._positions = [];
  38768. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38769. if (!data) {
  38770. return false;
  38771. }
  38772. for (var index = 0; index < data.length; index += 3) {
  38773. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38774. }
  38775. return true;
  38776. };
  38777. /**
  38778. * Gets a value indicating if the geometry is disposed
  38779. * @returns true if the geometry was disposed
  38780. */
  38781. Geometry.prototype.isDisposed = function () {
  38782. return this._isDisposed;
  38783. };
  38784. Geometry.prototype._disposeVertexArrayObjects = function () {
  38785. if (this._vertexArrayObjects) {
  38786. for (var kind in this._vertexArrayObjects) {
  38787. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38788. }
  38789. this._vertexArrayObjects = {};
  38790. }
  38791. };
  38792. /**
  38793. * Free all associated resources
  38794. */
  38795. Geometry.prototype.dispose = function () {
  38796. var meshes = this._meshes;
  38797. var numOfMeshes = meshes.length;
  38798. var index;
  38799. for (index = 0; index < numOfMeshes; index++) {
  38800. this.releaseForMesh(meshes[index]);
  38801. }
  38802. this._meshes = [];
  38803. this._disposeVertexArrayObjects();
  38804. for (var kind in this._vertexBuffers) {
  38805. this._vertexBuffers[kind].dispose();
  38806. }
  38807. this._vertexBuffers = {};
  38808. this._totalVertices = 0;
  38809. if (this._indexBuffer) {
  38810. this._engine._releaseBuffer(this._indexBuffer);
  38811. }
  38812. this._indexBuffer = null;
  38813. this._indices = [];
  38814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38815. this.delayLoadingFile = null;
  38816. this._delayLoadingFunction = null;
  38817. this._delayInfo = [];
  38818. this._boundingInfo = null;
  38819. this._scene.removeGeometry(this);
  38820. this._isDisposed = true;
  38821. };
  38822. /**
  38823. * Clone the current geometry into a new geometry
  38824. * @param id defines the unique ID of the new geometry
  38825. * @returns a new geometry object
  38826. */
  38827. Geometry.prototype.copy = function (id) {
  38828. var vertexData = new BABYLON.VertexData();
  38829. vertexData.indices = [];
  38830. var indices = this.getIndices();
  38831. if (indices) {
  38832. for (var index = 0; index < indices.length; index++) {
  38833. vertexData.indices.push(indices[index]);
  38834. }
  38835. }
  38836. var updatable = false;
  38837. var stopChecking = false;
  38838. var kind;
  38839. for (kind in this._vertexBuffers) {
  38840. // using slice() to make a copy of the array and not just reference it
  38841. var data = this.getVerticesData(kind);
  38842. if (data instanceof Float32Array) {
  38843. vertexData.set(new Float32Array(data), kind);
  38844. }
  38845. else {
  38846. vertexData.set(data.slice(0), kind);
  38847. }
  38848. if (!stopChecking) {
  38849. var vb = this.getVertexBuffer(kind);
  38850. if (vb) {
  38851. updatable = vb.isUpdatable();
  38852. stopChecking = !updatable;
  38853. }
  38854. }
  38855. }
  38856. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38857. geometry.delayLoadState = this.delayLoadState;
  38858. geometry.delayLoadingFile = this.delayLoadingFile;
  38859. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38860. for (kind in this._delayInfo) {
  38861. geometry._delayInfo = geometry._delayInfo || [];
  38862. geometry._delayInfo.push(kind);
  38863. }
  38864. // Bounding info
  38865. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38866. return geometry;
  38867. };
  38868. /**
  38869. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38870. * @return a JSON representation of the current geometry data (without the vertices data)
  38871. */
  38872. Geometry.prototype.serialize = function () {
  38873. var serializationObject = {};
  38874. serializationObject.id = this.id;
  38875. serializationObject.updatable = this._updatable;
  38876. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38877. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38878. }
  38879. return serializationObject;
  38880. };
  38881. Geometry.prototype.toNumberArray = function (origin) {
  38882. if (Array.isArray(origin)) {
  38883. return origin;
  38884. }
  38885. else {
  38886. return Array.prototype.slice.call(origin);
  38887. }
  38888. };
  38889. /**
  38890. * Serialize all vertices data into a JSON oject
  38891. * @returns a JSON representation of the current geometry data
  38892. */
  38893. Geometry.prototype.serializeVerticeData = function () {
  38894. var serializationObject = this.serialize();
  38895. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38896. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38897. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38898. serializationObject.positions._updatable = true;
  38899. }
  38900. }
  38901. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38902. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38903. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38904. serializationObject.normals._updatable = true;
  38905. }
  38906. }
  38907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38908. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38910. serializationObject.tangets._updatable = true;
  38911. }
  38912. }
  38913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38914. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38916. serializationObject.uvs._updatable = true;
  38917. }
  38918. }
  38919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38920. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38922. serializationObject.uv2s._updatable = true;
  38923. }
  38924. }
  38925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38926. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38928. serializationObject.uv3s._updatable = true;
  38929. }
  38930. }
  38931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38932. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38934. serializationObject.uv4s._updatable = true;
  38935. }
  38936. }
  38937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38938. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38940. serializationObject.uv5s._updatable = true;
  38941. }
  38942. }
  38943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38944. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38946. serializationObject.uv6s._updatable = true;
  38947. }
  38948. }
  38949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38950. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38952. serializationObject.colors._updatable = true;
  38953. }
  38954. }
  38955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38956. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38957. serializationObject.matricesIndices._isExpanded = true;
  38958. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38959. serializationObject.matricesIndices._updatable = true;
  38960. }
  38961. }
  38962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38963. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38965. serializationObject.matricesWeights._updatable = true;
  38966. }
  38967. }
  38968. serializationObject.indices = this.toNumberArray(this.getIndices());
  38969. return serializationObject;
  38970. };
  38971. // Statics
  38972. /**
  38973. * Extracts a clone of a mesh geometry
  38974. * @param mesh defines the source mesh
  38975. * @param id defines the unique ID of the new geometry object
  38976. * @returns the new geometry object
  38977. */
  38978. Geometry.ExtractFromMesh = function (mesh, id) {
  38979. var geometry = mesh._geometry;
  38980. if (!geometry) {
  38981. return null;
  38982. }
  38983. return geometry.copy(id);
  38984. };
  38985. /**
  38986. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38987. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38988. * Be aware Math.random() could cause collisions, but:
  38989. * "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"
  38990. * @returns a string containing a new GUID
  38991. */
  38992. Geometry.RandomId = function () {
  38993. return BABYLON.Tools.RandomId();
  38994. };
  38995. /** @ignore */
  38996. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38997. var scene = mesh.getScene();
  38998. // Geometry
  38999. var geometryId = parsedGeometry.geometryId;
  39000. if (geometryId) {
  39001. var geometry = scene.getGeometryByID(geometryId);
  39002. if (geometry) {
  39003. geometry.applyToMesh(mesh);
  39004. }
  39005. }
  39006. else if (parsedGeometry instanceof ArrayBuffer) {
  39007. var binaryInfo = mesh._binaryInfo;
  39008. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39009. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39010. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39011. }
  39012. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39013. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39014. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39015. }
  39016. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39017. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39018. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39019. }
  39020. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39021. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39022. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39023. }
  39024. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39025. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39026. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39027. }
  39028. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39029. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39030. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39031. }
  39032. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39033. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39034. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39035. }
  39036. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39037. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39038. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39039. }
  39040. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39041. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39042. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39043. }
  39044. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39045. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39046. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39047. }
  39048. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39049. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39050. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39051. }
  39052. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39053. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39054. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39055. }
  39056. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39057. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39058. mesh.setIndices(indicesData, null);
  39059. }
  39060. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39061. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39062. mesh.subMeshes = [];
  39063. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39064. var materialIndex = subMeshesData[(i * 5) + 0];
  39065. var verticesStart = subMeshesData[(i * 5) + 1];
  39066. var verticesCount = subMeshesData[(i * 5) + 2];
  39067. var indexStart = subMeshesData[(i * 5) + 3];
  39068. var indexCount = subMeshesData[(i * 5) + 4];
  39069. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39070. }
  39071. }
  39072. }
  39073. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39074. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39075. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39076. if (parsedGeometry.tangents) {
  39077. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39078. }
  39079. if (parsedGeometry.uvs) {
  39080. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39081. }
  39082. if (parsedGeometry.uvs2) {
  39083. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39084. }
  39085. if (parsedGeometry.uvs3) {
  39086. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39087. }
  39088. if (parsedGeometry.uvs4) {
  39089. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39090. }
  39091. if (parsedGeometry.uvs5) {
  39092. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39093. }
  39094. if (parsedGeometry.uvs6) {
  39095. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39096. }
  39097. if (parsedGeometry.colors) {
  39098. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39099. }
  39100. if (parsedGeometry.matricesIndices) {
  39101. if (!parsedGeometry.matricesIndices._isExpanded) {
  39102. var floatIndices = [];
  39103. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39104. var matricesIndex = parsedGeometry.matricesIndices[i];
  39105. floatIndices.push(matricesIndex & 0x000000FF);
  39106. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39107. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39108. floatIndices.push(matricesIndex >> 24);
  39109. }
  39110. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39111. }
  39112. else {
  39113. delete parsedGeometry.matricesIndices._isExpanded;
  39114. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39115. }
  39116. }
  39117. if (parsedGeometry.matricesIndicesExtra) {
  39118. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39119. var floatIndices = [];
  39120. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39121. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39122. floatIndices.push(matricesIndex & 0x000000FF);
  39123. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39124. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39125. floatIndices.push(matricesIndex >> 24);
  39126. }
  39127. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39128. }
  39129. else {
  39130. delete parsedGeometry.matricesIndices._isExpanded;
  39131. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39132. }
  39133. }
  39134. if (parsedGeometry.matricesWeights) {
  39135. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39136. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39137. }
  39138. if (parsedGeometry.matricesWeightsExtra) {
  39139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39140. }
  39141. mesh.setIndices(parsedGeometry.indices, null);
  39142. }
  39143. // SubMeshes
  39144. if (parsedGeometry.subMeshes) {
  39145. mesh.subMeshes = [];
  39146. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39147. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39148. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39149. }
  39150. }
  39151. // Flat shading
  39152. if (mesh._shouldGenerateFlatShading) {
  39153. mesh.convertToFlatShadedMesh();
  39154. delete mesh._shouldGenerateFlatShading;
  39155. }
  39156. // Update
  39157. mesh.computeWorldMatrix(true);
  39158. // Octree
  39159. var sceneOctree = scene.selectionOctree;
  39160. if (sceneOctree !== undefined && sceneOctree !== null) {
  39161. sceneOctree.addMesh(mesh);
  39162. }
  39163. };
  39164. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39165. var epsilon = 1e-3;
  39166. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39167. return;
  39168. }
  39169. var noInfluenceBoneIndex = 0.0;
  39170. if (parsedGeometry.skeletonId > -1) {
  39171. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39172. if (!skeleton) {
  39173. return;
  39174. }
  39175. noInfluenceBoneIndex = skeleton.bones.length;
  39176. }
  39177. else {
  39178. return;
  39179. }
  39180. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39181. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39182. var matricesWeights = parsedGeometry.matricesWeights;
  39183. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39184. var influencers = parsedGeometry.numBoneInfluencer;
  39185. var size = matricesWeights.length;
  39186. for (var i = 0; i < size; i += 4) {
  39187. var weight = 0.0;
  39188. var firstZeroWeight = -1;
  39189. for (var j = 0; j < 4; j++) {
  39190. var w = matricesWeights[i + j];
  39191. weight += w;
  39192. if (w < epsilon && firstZeroWeight < 0) {
  39193. firstZeroWeight = j;
  39194. }
  39195. }
  39196. if (matricesWeightsExtra) {
  39197. for (var j = 0; j < 4; j++) {
  39198. var w = matricesWeightsExtra[i + j];
  39199. weight += w;
  39200. if (w < epsilon && firstZeroWeight < 0) {
  39201. firstZeroWeight = j + 4;
  39202. }
  39203. }
  39204. }
  39205. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39206. firstZeroWeight = influencers - 1;
  39207. }
  39208. if (weight > epsilon) {
  39209. var mweight = 1.0 / weight;
  39210. for (var j = 0; j < 4; j++) {
  39211. matricesWeights[i + j] *= mweight;
  39212. }
  39213. if (matricesWeightsExtra) {
  39214. for (var j = 0; j < 4; j++) {
  39215. matricesWeightsExtra[i + j] *= mweight;
  39216. }
  39217. }
  39218. }
  39219. else {
  39220. if (firstZeroWeight >= 4) {
  39221. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39222. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39223. }
  39224. else {
  39225. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39226. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39227. }
  39228. }
  39229. }
  39230. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39231. if (parsedGeometry.matricesWeightsExtra) {
  39232. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39233. }
  39234. };
  39235. /**
  39236. * Create a new geometry from persisted data (Using .babylon file format)
  39237. * @param parsedVertexData defines the persisted data
  39238. * @param scene defines the hosting scene
  39239. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39240. * @returns the new geometry object
  39241. */
  39242. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39243. if (scene.getGeometryByID(parsedVertexData.id)) {
  39244. return null; // null since geometry could be something else than a box...
  39245. }
  39246. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39247. if (BABYLON.Tags) {
  39248. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39249. }
  39250. if (parsedVertexData.delayLoadingFile) {
  39251. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39252. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39253. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39254. geometry._delayInfo = [];
  39255. if (parsedVertexData.hasUVs) {
  39256. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39257. }
  39258. if (parsedVertexData.hasUVs2) {
  39259. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39260. }
  39261. if (parsedVertexData.hasUVs3) {
  39262. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39263. }
  39264. if (parsedVertexData.hasUVs4) {
  39265. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39266. }
  39267. if (parsedVertexData.hasUVs5) {
  39268. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39269. }
  39270. if (parsedVertexData.hasUVs6) {
  39271. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39272. }
  39273. if (parsedVertexData.hasColors) {
  39274. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39275. }
  39276. if (parsedVertexData.hasMatricesIndices) {
  39277. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39278. }
  39279. if (parsedVertexData.hasMatricesWeights) {
  39280. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39281. }
  39282. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39283. }
  39284. else {
  39285. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39286. }
  39287. scene.pushGeometry(geometry, true);
  39288. return geometry;
  39289. };
  39290. return Geometry;
  39291. }());
  39292. BABYLON.Geometry = Geometry;
  39293. // Primitives
  39294. /// Abstract class
  39295. /**
  39296. * Abstract class used to provide common services for all typed geometries
  39297. */
  39298. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39299. __extends(_PrimitiveGeometry, _super);
  39300. /**
  39301. * Creates a new typed geometry
  39302. * @param id defines the unique ID of the geometry
  39303. * @param scene defines the hosting scene
  39304. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39305. * @param mesh defines the hosting mesh (can be null)
  39306. */
  39307. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39308. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39309. if (mesh === void 0) { mesh = null; }
  39310. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39311. _this._canBeRegenerated = _canBeRegenerated;
  39312. _this._beingRegenerated = true;
  39313. _this.regenerate();
  39314. _this._beingRegenerated = false;
  39315. return _this;
  39316. }
  39317. /**
  39318. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39319. * @returns true if the geometry can be regenerated
  39320. */
  39321. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39322. return this._canBeRegenerated;
  39323. };
  39324. /**
  39325. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39326. */
  39327. _PrimitiveGeometry.prototype.regenerate = function () {
  39328. if (!this._canBeRegenerated) {
  39329. return;
  39330. }
  39331. this._beingRegenerated = true;
  39332. this.setAllVerticesData(this._regenerateVertexData(), false);
  39333. this._beingRegenerated = false;
  39334. };
  39335. /**
  39336. * Clone the geometry
  39337. * @param id defines the unique ID of the new geometry
  39338. * @returns the new geometry
  39339. */
  39340. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39341. return _super.prototype.copy.call(this, id);
  39342. };
  39343. // overrides
  39344. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39345. if (!this._beingRegenerated) {
  39346. return;
  39347. }
  39348. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39349. };
  39350. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39351. if (!this._beingRegenerated) {
  39352. return;
  39353. }
  39354. _super.prototype.setVerticesData.call(this, kind, data, false);
  39355. };
  39356. // to override
  39357. /** @ignore */
  39358. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39359. throw new Error("Abstract method");
  39360. };
  39361. _PrimitiveGeometry.prototype.copy = function (id) {
  39362. throw new Error("Must be overriden in sub-classes.");
  39363. };
  39364. _PrimitiveGeometry.prototype.serialize = function () {
  39365. var serializationObject = _super.prototype.serialize.call(this);
  39366. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39367. return serializationObject;
  39368. };
  39369. return _PrimitiveGeometry;
  39370. }(Geometry));
  39371. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39372. /**
  39373. * Creates a ribbon geometry
  39374. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39375. */
  39376. var RibbonGeometry = /** @class */ (function (_super) {
  39377. __extends(RibbonGeometry, _super);
  39378. /**
  39379. * Creates a ribbon geometry
  39380. * @param id defines the unique ID of the geometry
  39381. * @param scene defines the hosting scene
  39382. * @param pathArray defines the array of paths to use
  39383. * @param closeArray defines if the last path and the first path must be joined
  39384. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39385. * @param offset defines the offset between points
  39386. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39387. * @param mesh defines the hosting mesh (can be null)
  39388. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39389. */
  39390. function RibbonGeometry(id, scene,
  39391. /**
  39392. * Defines the array of paths to use
  39393. */
  39394. pathArray,
  39395. /**
  39396. * Defines if the last and first points of each path in your pathArray must be joined
  39397. */
  39398. closeArray,
  39399. /**
  39400. * Defines if the last and first points of each path in your pathArray must be joined
  39401. */
  39402. closePath,
  39403. /**
  39404. * Defines the offset between points
  39405. */
  39406. offset, canBeRegenerated, mesh,
  39407. /**
  39408. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39409. */
  39410. side) {
  39411. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39412. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39413. _this.pathArray = pathArray;
  39414. _this.closeArray = closeArray;
  39415. _this.closePath = closePath;
  39416. _this.offset = offset;
  39417. _this.side = side;
  39418. return _this;
  39419. }
  39420. /** @ignore */
  39421. RibbonGeometry.prototype._regenerateVertexData = function () {
  39422. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39423. };
  39424. RibbonGeometry.prototype.copy = function (id) {
  39425. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39426. };
  39427. return RibbonGeometry;
  39428. }(_PrimitiveGeometry));
  39429. BABYLON.RibbonGeometry = RibbonGeometry;
  39430. /**
  39431. * Creates a box geometry
  39432. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39433. */
  39434. var BoxGeometry = /** @class */ (function (_super) {
  39435. __extends(BoxGeometry, _super);
  39436. /**
  39437. * Creates a box geometry
  39438. * @param id defines the unique ID of the geometry
  39439. * @param scene defines the hosting scene
  39440. * @param size defines the zise of the box (width, height and depth are the same)
  39441. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39442. * @param mesh defines the hosting mesh (can be null)
  39443. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39444. */
  39445. function BoxGeometry(id, scene,
  39446. /**
  39447. * Defines the zise of the box (width, height and depth are the same)
  39448. */
  39449. size, canBeRegenerated, mesh,
  39450. /**
  39451. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39452. */
  39453. side) {
  39454. if (mesh === void 0) { mesh = null; }
  39455. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39456. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39457. _this.size = size;
  39458. _this.side = side;
  39459. return _this;
  39460. }
  39461. BoxGeometry.prototype._regenerateVertexData = function () {
  39462. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39463. };
  39464. BoxGeometry.prototype.copy = function (id) {
  39465. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39466. };
  39467. BoxGeometry.prototype.serialize = function () {
  39468. var serializationObject = _super.prototype.serialize.call(this);
  39469. serializationObject.size = this.size;
  39470. return serializationObject;
  39471. };
  39472. BoxGeometry.Parse = function (parsedBox, scene) {
  39473. if (scene.getGeometryByID(parsedBox.id)) {
  39474. return null; // null since geometry could be something else than a box...
  39475. }
  39476. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39477. if (BABYLON.Tags) {
  39478. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39479. }
  39480. scene.pushGeometry(box, true);
  39481. return box;
  39482. };
  39483. return BoxGeometry;
  39484. }(_PrimitiveGeometry));
  39485. BABYLON.BoxGeometry = BoxGeometry;
  39486. /**
  39487. * Creates a sphere geometry
  39488. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39489. */
  39490. var SphereGeometry = /** @class */ (function (_super) {
  39491. __extends(SphereGeometry, _super);
  39492. /**
  39493. * Create a new sphere geometry
  39494. * @param id defines the unique ID of the geometry
  39495. * @param scene defines the hosting scene
  39496. * @param segments defines the number of segments to use to create the sphere
  39497. * @param diameter defines the diameter of the sphere
  39498. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39499. * @param mesh defines the hosting mesh (can be null)
  39500. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39501. */
  39502. function SphereGeometry(id, scene,
  39503. /**
  39504. * Defines the number of segments to use to create the sphere
  39505. */
  39506. segments,
  39507. /**
  39508. * Defines the diameter of the sphere
  39509. */
  39510. diameter, canBeRegenerated, mesh,
  39511. /**
  39512. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39513. */
  39514. side) {
  39515. if (mesh === void 0) { mesh = null; }
  39516. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39517. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39518. _this.segments = segments;
  39519. _this.diameter = diameter;
  39520. _this.side = side;
  39521. return _this;
  39522. }
  39523. SphereGeometry.prototype._regenerateVertexData = function () {
  39524. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39525. };
  39526. SphereGeometry.prototype.copy = function (id) {
  39527. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39528. };
  39529. SphereGeometry.prototype.serialize = function () {
  39530. var serializationObject = _super.prototype.serialize.call(this);
  39531. serializationObject.segments = this.segments;
  39532. serializationObject.diameter = this.diameter;
  39533. return serializationObject;
  39534. };
  39535. SphereGeometry.Parse = function (parsedSphere, scene) {
  39536. if (scene.getGeometryByID(parsedSphere.id)) {
  39537. return null; // null since geometry could be something else than a sphere...
  39538. }
  39539. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39540. if (BABYLON.Tags) {
  39541. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39542. }
  39543. scene.pushGeometry(sphere, true);
  39544. return sphere;
  39545. };
  39546. return SphereGeometry;
  39547. }(_PrimitiveGeometry));
  39548. BABYLON.SphereGeometry = SphereGeometry;
  39549. /**
  39550. * Creates a disc geometry
  39551. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39552. */
  39553. var DiscGeometry = /** @class */ (function (_super) {
  39554. __extends(DiscGeometry, _super);
  39555. /**
  39556. * Creates a new disc geometry
  39557. * @param id defines the unique ID of the geometry
  39558. * @param scene defines the hosting scene
  39559. * @param radius defines the radius of the disc
  39560. * @param tessellation defines the tesselation factor to apply to the disc
  39561. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39562. * @param mesh defines the hosting mesh (can be null)
  39563. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39564. */
  39565. function DiscGeometry(id, scene,
  39566. /**
  39567. * Defines the radius of the disc
  39568. */
  39569. radius,
  39570. /**
  39571. * Defines the tesselation factor to apply to the disc
  39572. */
  39573. tessellation, canBeRegenerated, mesh,
  39574. /**
  39575. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39576. */
  39577. side) {
  39578. if (mesh === void 0) { mesh = null; }
  39579. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39580. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39581. _this.radius = radius;
  39582. _this.tessellation = tessellation;
  39583. _this.side = side;
  39584. return _this;
  39585. }
  39586. DiscGeometry.prototype._regenerateVertexData = function () {
  39587. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39588. };
  39589. DiscGeometry.prototype.copy = function (id) {
  39590. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39591. };
  39592. return DiscGeometry;
  39593. }(_PrimitiveGeometry));
  39594. BABYLON.DiscGeometry = DiscGeometry;
  39595. /**
  39596. * Creates a new cylinder geometry
  39597. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39598. */
  39599. var CylinderGeometry = /** @class */ (function (_super) {
  39600. __extends(CylinderGeometry, _super);
  39601. /**
  39602. * Creates a new cylinder geometry
  39603. * @param id defines the unique ID of the geometry
  39604. * @param scene defines the hosting scene
  39605. * @param height defines the height of the cylinder
  39606. * @param diameterTop defines the diameter of the cylinder's top cap
  39607. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39608. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39609. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39610. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39611. * @param mesh defines the hosting mesh (can be null)
  39612. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39613. */
  39614. function CylinderGeometry(id, scene,
  39615. /**
  39616. * Defines the height of the cylinder
  39617. */
  39618. height,
  39619. /**
  39620. * Defines the diameter of the cylinder's top cap
  39621. */
  39622. diameterTop,
  39623. /**
  39624. * Defines the diameter of the cylinder's bottom cap
  39625. */
  39626. diameterBottom,
  39627. /**
  39628. * Defines the tessellation factor to apply to the cylinder
  39629. */
  39630. tessellation,
  39631. /**
  39632. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39633. */
  39634. subdivisions, canBeRegenerated, mesh,
  39635. /**
  39636. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39637. */
  39638. side) {
  39639. if (subdivisions === void 0) { subdivisions = 1; }
  39640. if (mesh === void 0) { mesh = null; }
  39641. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39642. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39643. _this.height = height;
  39644. _this.diameterTop = diameterTop;
  39645. _this.diameterBottom = diameterBottom;
  39646. _this.tessellation = tessellation;
  39647. _this.subdivisions = subdivisions;
  39648. _this.side = side;
  39649. return _this;
  39650. }
  39651. CylinderGeometry.prototype._regenerateVertexData = function () {
  39652. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39653. };
  39654. CylinderGeometry.prototype.copy = function (id) {
  39655. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39656. };
  39657. CylinderGeometry.prototype.serialize = function () {
  39658. var serializationObject = _super.prototype.serialize.call(this);
  39659. serializationObject.height = this.height;
  39660. serializationObject.diameterTop = this.diameterTop;
  39661. serializationObject.diameterBottom = this.diameterBottom;
  39662. serializationObject.tessellation = this.tessellation;
  39663. return serializationObject;
  39664. };
  39665. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39666. if (scene.getGeometryByID(parsedCylinder.id)) {
  39667. return null; // null since geometry could be something else than a cylinder...
  39668. }
  39669. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39670. if (BABYLON.Tags) {
  39671. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39672. }
  39673. scene.pushGeometry(cylinder, true);
  39674. return cylinder;
  39675. };
  39676. return CylinderGeometry;
  39677. }(_PrimitiveGeometry));
  39678. BABYLON.CylinderGeometry = CylinderGeometry;
  39679. /**
  39680. * Creates a new torus geometry
  39681. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39682. */
  39683. var TorusGeometry = /** @class */ (function (_super) {
  39684. __extends(TorusGeometry, _super);
  39685. /**
  39686. * Creates a new torus geometry
  39687. * @param id defines the unique ID of the geometry
  39688. * @param scene defines the hosting scene
  39689. * @param diameter defines the diameter of the torus
  39690. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39691. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39692. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39693. * @param mesh defines the hosting mesh (can be null)
  39694. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39695. */
  39696. function TorusGeometry(id, scene,
  39697. /**
  39698. * Defines the diameter of the torus
  39699. */
  39700. diameter,
  39701. /**
  39702. * Defines the thickness of the torus (ie. internal diameter)
  39703. */
  39704. thickness,
  39705. /**
  39706. * Defines the tesselation factor to apply to the torus
  39707. */
  39708. tessellation, canBeRegenerated, mesh,
  39709. /**
  39710. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39711. */
  39712. side) {
  39713. if (mesh === void 0) { mesh = null; }
  39714. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39715. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39716. _this.diameter = diameter;
  39717. _this.thickness = thickness;
  39718. _this.tessellation = tessellation;
  39719. _this.side = side;
  39720. return _this;
  39721. }
  39722. TorusGeometry.prototype._regenerateVertexData = function () {
  39723. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39724. };
  39725. TorusGeometry.prototype.copy = function (id) {
  39726. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39727. };
  39728. TorusGeometry.prototype.serialize = function () {
  39729. var serializationObject = _super.prototype.serialize.call(this);
  39730. serializationObject.diameter = this.diameter;
  39731. serializationObject.thickness = this.thickness;
  39732. serializationObject.tessellation = this.tessellation;
  39733. return serializationObject;
  39734. };
  39735. TorusGeometry.Parse = function (parsedTorus, scene) {
  39736. if (scene.getGeometryByID(parsedTorus.id)) {
  39737. return null; // null since geometry could be something else than a torus...
  39738. }
  39739. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39740. if (BABYLON.Tags) {
  39741. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39742. }
  39743. scene.pushGeometry(torus, true);
  39744. return torus;
  39745. };
  39746. return TorusGeometry;
  39747. }(_PrimitiveGeometry));
  39748. BABYLON.TorusGeometry = TorusGeometry;
  39749. /**
  39750. * Creates a new ground geometry
  39751. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39752. */
  39753. var GroundGeometry = /** @class */ (function (_super) {
  39754. __extends(GroundGeometry, _super);
  39755. /**
  39756. * Creates a new ground geometry
  39757. * @param id defines the unique ID of the geometry
  39758. * @param scene defines the hosting scene
  39759. * @param width defines the width of the ground
  39760. * @param height defines the height of the ground
  39761. * @param subdivisions defines the subdivisions to apply to the ground
  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. */
  39765. function GroundGeometry(id, scene,
  39766. /**
  39767. * Defines the width of the ground
  39768. */
  39769. width,
  39770. /**
  39771. * Defines the height of the ground
  39772. */
  39773. height,
  39774. /**
  39775. * Defines the subdivisions to apply to the ground
  39776. */
  39777. subdivisions, canBeRegenerated, mesh) {
  39778. if (mesh === void 0) { mesh = null; }
  39779. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39780. _this.width = width;
  39781. _this.height = height;
  39782. _this.subdivisions = subdivisions;
  39783. return _this;
  39784. }
  39785. GroundGeometry.prototype._regenerateVertexData = function () {
  39786. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39787. };
  39788. GroundGeometry.prototype.copy = function (id) {
  39789. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39790. };
  39791. GroundGeometry.prototype.serialize = function () {
  39792. var serializationObject = _super.prototype.serialize.call(this);
  39793. serializationObject.width = this.width;
  39794. serializationObject.height = this.height;
  39795. serializationObject.subdivisions = this.subdivisions;
  39796. return serializationObject;
  39797. };
  39798. GroundGeometry.Parse = function (parsedGround, scene) {
  39799. if (scene.getGeometryByID(parsedGround.id)) {
  39800. return null; // null since geometry could be something else than a ground...
  39801. }
  39802. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39803. if (BABYLON.Tags) {
  39804. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39805. }
  39806. scene.pushGeometry(ground, true);
  39807. return ground;
  39808. };
  39809. return GroundGeometry;
  39810. }(_PrimitiveGeometry));
  39811. BABYLON.GroundGeometry = GroundGeometry;
  39812. /**
  39813. * Creates a tiled ground geometry
  39814. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39815. */
  39816. var TiledGroundGeometry = /** @class */ (function (_super) {
  39817. __extends(TiledGroundGeometry, _super);
  39818. /**
  39819. * Creates a tiled ground geometry
  39820. * @param id defines the unique ID of the geometry
  39821. * @param scene defines the hosting scene
  39822. * @param xmin defines the minimum value on X axis
  39823. * @param zmin defines the minimum value on Z axis
  39824. * @param xmax defines the maximum value on X axis
  39825. * @param zmax defines the maximum value on Z axis
  39826. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39827. * @param precision defines the precision to use when computing the tiles
  39828. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39829. * @param mesh defines the hosting mesh (can be null)
  39830. */
  39831. function TiledGroundGeometry(id, scene,
  39832. /**
  39833. * Defines the minimum value on X axis
  39834. */
  39835. xmin,
  39836. /**
  39837. * Defines the minimum value on Z axis
  39838. */
  39839. zmin,
  39840. /**
  39841. * Defines the maximum value on X axis
  39842. */
  39843. xmax,
  39844. /**
  39845. * Defines the maximum value on Z axis
  39846. */
  39847. zmax,
  39848. /**
  39849. * Defines the subdivisions to apply to the ground
  39850. */
  39851. subdivisions,
  39852. /**
  39853. * Defines the precision to use when computing the tiles
  39854. */
  39855. precision, canBeRegenerated, mesh) {
  39856. if (mesh === void 0) { mesh = null; }
  39857. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39858. _this.xmin = xmin;
  39859. _this.zmin = zmin;
  39860. _this.xmax = xmax;
  39861. _this.zmax = zmax;
  39862. _this.subdivisions = subdivisions;
  39863. _this.precision = precision;
  39864. return _this;
  39865. }
  39866. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39867. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39868. };
  39869. TiledGroundGeometry.prototype.copy = function (id) {
  39870. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39871. };
  39872. return TiledGroundGeometry;
  39873. }(_PrimitiveGeometry));
  39874. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39875. /**
  39876. * Creates a plane geometry
  39877. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39878. */
  39879. var PlaneGeometry = /** @class */ (function (_super) {
  39880. __extends(PlaneGeometry, _super);
  39881. /**
  39882. * Creates a plane geometry
  39883. * @param id defines the unique ID of the geometry
  39884. * @param scene defines the hosting scene
  39885. * @param size defines the size of the plane (width === height)
  39886. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39887. * @param mesh defines the hosting mesh (can be null)
  39888. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39889. */
  39890. function PlaneGeometry(id, scene,
  39891. /**
  39892. * Defines the size of the plane (width === height)
  39893. */
  39894. size, canBeRegenerated, mesh,
  39895. /**
  39896. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39897. */
  39898. side) {
  39899. if (mesh === void 0) { mesh = null; }
  39900. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39901. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39902. _this.size = size;
  39903. _this.side = side;
  39904. return _this;
  39905. }
  39906. PlaneGeometry.prototype._regenerateVertexData = function () {
  39907. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39908. };
  39909. PlaneGeometry.prototype.copy = function (id) {
  39910. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39911. };
  39912. PlaneGeometry.prototype.serialize = function () {
  39913. var serializationObject = _super.prototype.serialize.call(this);
  39914. serializationObject.size = this.size;
  39915. return serializationObject;
  39916. };
  39917. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39918. if (scene.getGeometryByID(parsedPlane.id)) {
  39919. return null; // null since geometry could be something else than a ground...
  39920. }
  39921. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39922. if (BABYLON.Tags) {
  39923. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39924. }
  39925. scene.pushGeometry(plane, true);
  39926. return plane;
  39927. };
  39928. return PlaneGeometry;
  39929. }(_PrimitiveGeometry));
  39930. BABYLON.PlaneGeometry = PlaneGeometry;
  39931. /**
  39932. * Creates a torus knot geometry
  39933. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39934. */
  39935. var TorusKnotGeometry = /** @class */ (function (_super) {
  39936. __extends(TorusKnotGeometry, _super);
  39937. /**
  39938. * Creates a torus knot geometry
  39939. * @param id defines the unique ID of the geometry
  39940. * @param scene defines the hosting scene
  39941. * @param radius defines the radius of the torus knot
  39942. * @param tube defines the thickness of the torus knot tube
  39943. * @param radialSegments defines the number of radial segments
  39944. * @param tubularSegments defines the number of tubular segments
  39945. * @param p defines the first number of windings
  39946. * @param q defines the second number of windings
  39947. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39948. * @param mesh defines the hosting mesh (can be null)
  39949. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39950. */
  39951. function TorusKnotGeometry(id, scene,
  39952. /**
  39953. * Defines the radius of the torus knot
  39954. */
  39955. radius,
  39956. /**
  39957. * Defines the thickness of the torus knot tube
  39958. */
  39959. tube,
  39960. /**
  39961. * Defines the number of radial segments
  39962. */
  39963. radialSegments,
  39964. /**
  39965. * Defines the number of tubular segments
  39966. */
  39967. tubularSegments,
  39968. /**
  39969. * Defines the first number of windings
  39970. */
  39971. p,
  39972. /**
  39973. * Defines the second number of windings
  39974. */
  39975. q, canBeRegenerated, mesh,
  39976. /**
  39977. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39978. */
  39979. side) {
  39980. if (mesh === void 0) { mesh = null; }
  39981. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39982. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39983. _this.radius = radius;
  39984. _this.tube = tube;
  39985. _this.radialSegments = radialSegments;
  39986. _this.tubularSegments = tubularSegments;
  39987. _this.p = p;
  39988. _this.q = q;
  39989. _this.side = side;
  39990. return _this;
  39991. }
  39992. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39993. 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 });
  39994. };
  39995. TorusKnotGeometry.prototype.copy = function (id) {
  39996. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39997. };
  39998. TorusKnotGeometry.prototype.serialize = function () {
  39999. var serializationObject = _super.prototype.serialize.call(this);
  40000. serializationObject.radius = this.radius;
  40001. serializationObject.tube = this.tube;
  40002. serializationObject.radialSegments = this.radialSegments;
  40003. serializationObject.tubularSegments = this.tubularSegments;
  40004. serializationObject.p = this.p;
  40005. serializationObject.q = this.q;
  40006. return serializationObject;
  40007. };
  40008. ;
  40009. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40010. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40011. return null; // null since geometry could be something else than a ground...
  40012. }
  40013. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40014. if (BABYLON.Tags) {
  40015. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40016. }
  40017. scene.pushGeometry(torusKnot, true);
  40018. return torusKnot;
  40019. };
  40020. return TorusKnotGeometry;
  40021. }(_PrimitiveGeometry));
  40022. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40023. //}
  40024. })(BABYLON || (BABYLON = {}));
  40025. //# sourceMappingURL=babylon.geometry.js.map
  40026. "use strict";
  40027. var BABYLON;
  40028. (function (BABYLON) {
  40029. /**
  40030. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40031. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40032. */
  40033. var PostProcessManager = /** @class */ (function () {
  40034. /**
  40035. * Creates a new instance PostProcess
  40036. * @param scene The scene that the post process is associated with.
  40037. */
  40038. function PostProcessManager(scene) {
  40039. this._vertexBuffers = {};
  40040. this._scene = scene;
  40041. }
  40042. PostProcessManager.prototype._prepareBuffers = function () {
  40043. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40044. return;
  40045. }
  40046. // VBO
  40047. var vertices = [];
  40048. vertices.push(1, 1);
  40049. vertices.push(-1, 1);
  40050. vertices.push(-1, -1);
  40051. vertices.push(1, -1);
  40052. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40053. this._buildIndexBuffer();
  40054. };
  40055. PostProcessManager.prototype._buildIndexBuffer = function () {
  40056. // Indices
  40057. var indices = [];
  40058. indices.push(0);
  40059. indices.push(1);
  40060. indices.push(2);
  40061. indices.push(0);
  40062. indices.push(2);
  40063. indices.push(3);
  40064. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40065. };
  40066. /**
  40067. * Rebuilds the vertex buffers of the manager.
  40068. */
  40069. PostProcessManager.prototype._rebuild = function () {
  40070. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40071. if (!vb) {
  40072. return;
  40073. }
  40074. vb._rebuild();
  40075. this._buildIndexBuffer();
  40076. };
  40077. // Methods
  40078. /**
  40079. * Prepares a frame to be run through a post process.
  40080. * @param sourceTexture The input texture to the post procesess. (default: null)
  40081. * @param postProcesses An array of post processes to be run. (default: null)
  40082. * @returns True if the post processes were able to be run.
  40083. */
  40084. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40085. if (sourceTexture === void 0) { sourceTexture = null; }
  40086. if (postProcesses === void 0) { postProcesses = null; }
  40087. var camera = this._scene.activeCamera;
  40088. if (!camera) {
  40089. return false;
  40090. }
  40091. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40092. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40093. return false;
  40094. }
  40095. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40096. return true;
  40097. };
  40098. /**
  40099. * Manually render a set of post processes to a texture.
  40100. * @param postProcesses An array of post processes to be run.
  40101. * @param targetTexture The target texture to render to.
  40102. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40103. */
  40104. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40105. if (targetTexture === void 0) { targetTexture = null; }
  40106. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40107. var engine = this._scene.getEngine();
  40108. for (var index = 0; index < postProcesses.length; index++) {
  40109. if (index < postProcesses.length - 1) {
  40110. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40111. }
  40112. else {
  40113. if (targetTexture) {
  40114. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40115. }
  40116. else {
  40117. engine.restoreDefaultFramebuffer();
  40118. }
  40119. }
  40120. var pp = postProcesses[index];
  40121. var effect = pp.apply();
  40122. if (effect) {
  40123. pp.onBeforeRenderObservable.notifyObservers(effect);
  40124. // VBOs
  40125. this._prepareBuffers();
  40126. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40127. // Draw order
  40128. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40129. pp.onAfterRenderObservable.notifyObservers(effect);
  40130. }
  40131. }
  40132. // Restore depth buffer
  40133. engine.setDepthBuffer(true);
  40134. engine.setDepthWrite(true);
  40135. };
  40136. /**
  40137. * Finalize the result of the output of the postprocesses.
  40138. * @param doNotPresent If true the result will not be displayed to the screen.
  40139. * @param targetTexture The target texture to render to.
  40140. * @param faceIndex The index of the face to bind the target texture to.
  40141. * @param postProcesses The array of post processes to render.
  40142. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40143. */
  40144. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40145. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40146. var camera = this._scene.activeCamera;
  40147. if (!camera) {
  40148. return;
  40149. }
  40150. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40151. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40152. return;
  40153. }
  40154. var engine = this._scene.getEngine();
  40155. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40156. var pp = postProcesses[index];
  40157. if (index < len - 1) {
  40158. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40159. }
  40160. else {
  40161. if (targetTexture) {
  40162. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40163. pp._outputTexture = targetTexture;
  40164. }
  40165. else {
  40166. engine.restoreDefaultFramebuffer();
  40167. pp._outputTexture = null;
  40168. }
  40169. }
  40170. if (doNotPresent) {
  40171. break;
  40172. }
  40173. var effect = pp.apply();
  40174. if (effect) {
  40175. pp.onBeforeRenderObservable.notifyObservers(effect);
  40176. // VBOs
  40177. this._prepareBuffers();
  40178. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40179. // Draw order
  40180. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40181. pp.onAfterRenderObservable.notifyObservers(effect);
  40182. }
  40183. }
  40184. // Restore states
  40185. engine.setDepthBuffer(true);
  40186. engine.setDepthWrite(true);
  40187. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40188. };
  40189. /**
  40190. * Disposes of the post process manager.
  40191. */
  40192. PostProcessManager.prototype.dispose = function () {
  40193. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40194. if (buffer) {
  40195. buffer.dispose();
  40196. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40197. }
  40198. if (this._indexBuffer) {
  40199. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40200. this._indexBuffer = null;
  40201. }
  40202. };
  40203. return PostProcessManager;
  40204. }());
  40205. BABYLON.PostProcessManager = PostProcessManager;
  40206. })(BABYLON || (BABYLON = {}));
  40207. //# sourceMappingURL=babylon.postProcessManager.js.map
  40208. "use strict";
  40209. var BABYLON;
  40210. (function (BABYLON) {
  40211. /**
  40212. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40213. */
  40214. var PerformanceMonitor = /** @class */ (function () {
  40215. /**
  40216. * constructor
  40217. * @param frameSampleSize The number of samples required to saturate the sliding window
  40218. */
  40219. function PerformanceMonitor(frameSampleSize) {
  40220. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40221. this._enabled = true;
  40222. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40223. }
  40224. /**
  40225. * Samples current frame
  40226. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40227. */
  40228. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40229. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40230. if (!this._enabled)
  40231. return;
  40232. if (this._lastFrameTimeMs != null) {
  40233. var dt = timeMs - this._lastFrameTimeMs;
  40234. this._rollingFrameTime.add(dt);
  40235. }
  40236. this._lastFrameTimeMs = timeMs;
  40237. };
  40238. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40239. /**
  40240. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40241. * @return Average frame time in milliseconds
  40242. */
  40243. get: function () {
  40244. return this._rollingFrameTime.average;
  40245. },
  40246. enumerable: true,
  40247. configurable: true
  40248. });
  40249. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40250. /**
  40251. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40252. * @return Frame time variance in milliseconds squared
  40253. */
  40254. get: function () {
  40255. return this._rollingFrameTime.variance;
  40256. },
  40257. enumerable: true,
  40258. configurable: true
  40259. });
  40260. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40261. /**
  40262. * Returns the frame time of the most recent frame
  40263. * @return Frame time in milliseconds
  40264. */
  40265. get: function () {
  40266. return this._rollingFrameTime.history(0);
  40267. },
  40268. enumerable: true,
  40269. configurable: true
  40270. });
  40271. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40272. /**
  40273. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40274. * @return Framerate in frames per second
  40275. */
  40276. get: function () {
  40277. return 1000.0 / this._rollingFrameTime.average;
  40278. },
  40279. enumerable: true,
  40280. configurable: true
  40281. });
  40282. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40283. /**
  40284. * Returns the average framerate in frames per second using the most recent frame time
  40285. * @return Framerate in frames per second
  40286. */
  40287. get: function () {
  40288. var history = this._rollingFrameTime.history(0);
  40289. if (history === 0) {
  40290. return 0;
  40291. }
  40292. return 1000.0 / history;
  40293. },
  40294. enumerable: true,
  40295. configurable: true
  40296. });
  40297. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40298. /**
  40299. * Returns true if enough samples have been taken to completely fill the sliding window
  40300. * @return true if saturated
  40301. */
  40302. get: function () {
  40303. return this._rollingFrameTime.isSaturated();
  40304. },
  40305. enumerable: true,
  40306. configurable: true
  40307. });
  40308. /**
  40309. * Enables contributions to the sliding window sample set
  40310. */
  40311. PerformanceMonitor.prototype.enable = function () {
  40312. this._enabled = true;
  40313. };
  40314. /**
  40315. * Disables contributions to the sliding window sample set
  40316. * Samples will not be interpolated over the disabled period
  40317. */
  40318. PerformanceMonitor.prototype.disable = function () {
  40319. this._enabled = false;
  40320. //clear last sample to avoid interpolating over the disabled period when next enabled
  40321. this._lastFrameTimeMs = null;
  40322. };
  40323. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40324. /**
  40325. * Returns true if sampling is enabled
  40326. * @return true if enabled
  40327. */
  40328. get: function () {
  40329. return this._enabled;
  40330. },
  40331. enumerable: true,
  40332. configurable: true
  40333. });
  40334. /**
  40335. * Resets performance monitor
  40336. */
  40337. PerformanceMonitor.prototype.reset = function () {
  40338. //clear last sample to avoid interpolating over the disabled period when next enabled
  40339. this._lastFrameTimeMs = null;
  40340. //wipe record
  40341. this._rollingFrameTime.reset();
  40342. };
  40343. return PerformanceMonitor;
  40344. }());
  40345. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40346. /**
  40347. * RollingAverage
  40348. *
  40349. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40350. */
  40351. var RollingAverage = /** @class */ (function () {
  40352. /**
  40353. * constructor
  40354. * @param length The number of samples required to saturate the sliding window
  40355. */
  40356. function RollingAverage(length) {
  40357. this._samples = new Array(length);
  40358. this.reset();
  40359. }
  40360. /**
  40361. * Adds a sample to the sample set
  40362. * @param v The sample value
  40363. */
  40364. RollingAverage.prototype.add = function (v) {
  40365. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40366. var delta;
  40367. //we need to check if we've already wrapped round
  40368. if (this.isSaturated()) {
  40369. //remove bottom of stack from mean
  40370. var bottomValue = this._samples[this._pos];
  40371. delta = bottomValue - this.average;
  40372. this.average -= delta / (this._sampleCount - 1);
  40373. this._m2 -= delta * (bottomValue - this.average);
  40374. }
  40375. else {
  40376. this._sampleCount++;
  40377. }
  40378. //add new value to mean
  40379. delta = v - this.average;
  40380. this.average += delta / (this._sampleCount);
  40381. this._m2 += delta * (v - this.average);
  40382. //set the new variance
  40383. this.variance = this._m2 / (this._sampleCount - 1);
  40384. this._samples[this._pos] = v;
  40385. this._pos++;
  40386. this._pos %= this._samples.length; //positive wrap around
  40387. };
  40388. /**
  40389. * Returns previously added values or null if outside of history or outside the sliding window domain
  40390. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40391. * @return Value previously recorded with add() or null if outside of range
  40392. */
  40393. RollingAverage.prototype.history = function (i) {
  40394. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40395. return 0;
  40396. }
  40397. var i0 = this._wrapPosition(this._pos - 1.0);
  40398. return this._samples[this._wrapPosition(i0 - i)];
  40399. };
  40400. /**
  40401. * Returns true if enough samples have been taken to completely fill the sliding window
  40402. * @return true if sample-set saturated
  40403. */
  40404. RollingAverage.prototype.isSaturated = function () {
  40405. return this._sampleCount >= this._samples.length;
  40406. };
  40407. /**
  40408. * Resets the rolling average (equivalent to 0 samples taken so far)
  40409. */
  40410. RollingAverage.prototype.reset = function () {
  40411. this.average = 0;
  40412. this.variance = 0;
  40413. this._sampleCount = 0;
  40414. this._pos = 0;
  40415. this._m2 = 0;
  40416. };
  40417. /**
  40418. * Wraps a value around the sample range boundaries
  40419. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40420. * @return Wrapped position in sample range
  40421. */
  40422. RollingAverage.prototype._wrapPosition = function (i) {
  40423. var max = this._samples.length;
  40424. return ((i % max) + max) % max;
  40425. };
  40426. return RollingAverage;
  40427. }());
  40428. BABYLON.RollingAverage = RollingAverage;
  40429. })(BABYLON || (BABYLON = {}));
  40430. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40431. "use strict";
  40432. var BABYLON;
  40433. (function (BABYLON) {
  40434. /**
  40435. * This groups together the common properties used for image processing either in direct forward pass
  40436. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40437. * or not.
  40438. */
  40439. var ImageProcessingConfiguration = /** @class */ (function () {
  40440. function ImageProcessingConfiguration() {
  40441. /**
  40442. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40443. */
  40444. this.colorCurves = new BABYLON.ColorCurves();
  40445. this._colorCurvesEnabled = false;
  40446. this._colorGradingEnabled = false;
  40447. this._colorGradingWithGreenDepth = true;
  40448. this._colorGradingBGR = true;
  40449. this._exposure = 1.0;
  40450. this._toneMappingEnabled = false;
  40451. this._contrast = 1.0;
  40452. /**
  40453. * Vignette stretch size.
  40454. */
  40455. this.vignetteStretch = 0;
  40456. /**
  40457. * Vignette centre X Offset.
  40458. */
  40459. this.vignetteCentreX = 0;
  40460. /**
  40461. * Vignette centre Y Offset.
  40462. */
  40463. this.vignetteCentreY = 0;
  40464. /**
  40465. * Vignette weight or intensity of the vignette effect.
  40466. */
  40467. this.vignetteWeight = 1.5;
  40468. /**
  40469. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40470. * if vignetteEnabled is set to true.
  40471. */
  40472. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40473. /**
  40474. * Camera field of view used by the Vignette effect.
  40475. */
  40476. this.vignetteCameraFov = 0.5;
  40477. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40478. this._vignetteEnabled = false;
  40479. this._applyByPostProcess = false;
  40480. this._isEnabled = true;
  40481. /**
  40482. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40483. */
  40484. this.onUpdateParameters = new BABYLON.Observable();
  40485. }
  40486. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40487. /**
  40488. * Gets wether the color curves effect is enabled.
  40489. */
  40490. get: function () {
  40491. return this._colorCurvesEnabled;
  40492. },
  40493. /**
  40494. * Sets wether the color curves effect is enabled.
  40495. */
  40496. set: function (value) {
  40497. if (this._colorCurvesEnabled === value) {
  40498. return;
  40499. }
  40500. this._colorCurvesEnabled = value;
  40501. this._updateParameters();
  40502. },
  40503. enumerable: true,
  40504. configurable: true
  40505. });
  40506. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40507. /**
  40508. * Gets wether the color grading effect is enabled.
  40509. */
  40510. get: function () {
  40511. return this._colorGradingEnabled;
  40512. },
  40513. /**
  40514. * Sets wether the color grading effect is enabled.
  40515. */
  40516. set: function (value) {
  40517. if (this._colorGradingEnabled === value) {
  40518. return;
  40519. }
  40520. this._colorGradingEnabled = value;
  40521. this._updateParameters();
  40522. },
  40523. enumerable: true,
  40524. configurable: true
  40525. });
  40526. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40527. /**
  40528. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40529. */
  40530. get: function () {
  40531. return this._colorGradingWithGreenDepth;
  40532. },
  40533. /**
  40534. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40535. */
  40536. set: function (value) {
  40537. if (this._colorGradingWithGreenDepth === value) {
  40538. return;
  40539. }
  40540. this._colorGradingWithGreenDepth = value;
  40541. this._updateParameters();
  40542. },
  40543. enumerable: true,
  40544. configurable: true
  40545. });
  40546. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40547. /**
  40548. * Gets wether the color grading texture contains BGR values.
  40549. */
  40550. get: function () {
  40551. return this._colorGradingBGR;
  40552. },
  40553. /**
  40554. * Sets wether the color grading texture contains BGR values.
  40555. */
  40556. set: function (value) {
  40557. if (this._colorGradingBGR === value) {
  40558. return;
  40559. }
  40560. this._colorGradingBGR = value;
  40561. this._updateParameters();
  40562. },
  40563. enumerable: true,
  40564. configurable: true
  40565. });
  40566. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40567. /**
  40568. * Gets the Exposure used in the effect.
  40569. */
  40570. get: function () {
  40571. return this._exposure;
  40572. },
  40573. /**
  40574. * Sets the Exposure used in the effect.
  40575. */
  40576. set: function (value) {
  40577. if (this._exposure === value) {
  40578. return;
  40579. }
  40580. this._exposure = value;
  40581. this._updateParameters();
  40582. },
  40583. enumerable: true,
  40584. configurable: true
  40585. });
  40586. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40587. /**
  40588. * Gets wether the tone mapping effect is enabled.
  40589. */
  40590. get: function () {
  40591. return this._toneMappingEnabled;
  40592. },
  40593. /**
  40594. * Sets wether the tone mapping effect is enabled.
  40595. */
  40596. set: function (value) {
  40597. if (this._toneMappingEnabled === value) {
  40598. return;
  40599. }
  40600. this._toneMappingEnabled = value;
  40601. this._updateParameters();
  40602. },
  40603. enumerable: true,
  40604. configurable: true
  40605. });
  40606. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40607. /**
  40608. * Gets the contrast used in the effect.
  40609. */
  40610. get: function () {
  40611. return this._contrast;
  40612. },
  40613. /**
  40614. * Sets the contrast used in the effect.
  40615. */
  40616. set: function (value) {
  40617. if (this._contrast === value) {
  40618. return;
  40619. }
  40620. this._contrast = value;
  40621. this._updateParameters();
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40627. /**
  40628. * Gets the vignette blend mode allowing different kind of effect.
  40629. */
  40630. get: function () {
  40631. return this._vignetteBlendMode;
  40632. },
  40633. /**
  40634. * Sets the vignette blend mode allowing different kind of effect.
  40635. */
  40636. set: function (value) {
  40637. if (this._vignetteBlendMode === value) {
  40638. return;
  40639. }
  40640. this._vignetteBlendMode = value;
  40641. this._updateParameters();
  40642. },
  40643. enumerable: true,
  40644. configurable: true
  40645. });
  40646. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40647. /**
  40648. * Gets wether the vignette effect is enabled.
  40649. */
  40650. get: function () {
  40651. return this._vignetteEnabled;
  40652. },
  40653. /**
  40654. * Sets wether the vignette effect is enabled.
  40655. */
  40656. set: function (value) {
  40657. if (this._vignetteEnabled === value) {
  40658. return;
  40659. }
  40660. this._vignetteEnabled = value;
  40661. this._updateParameters();
  40662. },
  40663. enumerable: true,
  40664. configurable: true
  40665. });
  40666. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40667. /**
  40668. * Gets wether the image processing is applied through a post process or not.
  40669. */
  40670. get: function () {
  40671. return this._applyByPostProcess;
  40672. },
  40673. /**
  40674. * Sets wether the image processing is applied through a post process or not.
  40675. */
  40676. set: function (value) {
  40677. if (this._applyByPostProcess === value) {
  40678. return;
  40679. }
  40680. this._applyByPostProcess = value;
  40681. this._updateParameters();
  40682. },
  40683. enumerable: true,
  40684. configurable: true
  40685. });
  40686. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40687. /**
  40688. * Gets wether the image processing is enabled or not.
  40689. */
  40690. get: function () {
  40691. return this._isEnabled;
  40692. },
  40693. /**
  40694. * Sets wether the image processing is enabled or not.
  40695. */
  40696. set: function (value) {
  40697. if (this._isEnabled === value) {
  40698. return;
  40699. }
  40700. this._isEnabled = value;
  40701. this._updateParameters();
  40702. },
  40703. enumerable: true,
  40704. configurable: true
  40705. });
  40706. /**
  40707. * Method called each time the image processing information changes requires to recompile the effect.
  40708. */
  40709. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40710. this.onUpdateParameters.notifyObservers(this);
  40711. };
  40712. ImageProcessingConfiguration.prototype.getClassName = function () {
  40713. return "ImageProcessingConfiguration";
  40714. };
  40715. /**
  40716. * Prepare the list of uniforms associated with the Image Processing effects.
  40717. * @param uniformsList The list of uniforms used in the effect
  40718. * @param defines the list of defines currently in use
  40719. */
  40720. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40721. if (defines.EXPOSURE) {
  40722. uniforms.push("exposureLinear");
  40723. }
  40724. if (defines.CONTRAST) {
  40725. uniforms.push("contrast");
  40726. }
  40727. if (defines.COLORGRADING) {
  40728. uniforms.push("colorTransformSettings");
  40729. }
  40730. if (defines.VIGNETTE) {
  40731. uniforms.push("vInverseScreenSize");
  40732. uniforms.push("vignetteSettings1");
  40733. uniforms.push("vignetteSettings2");
  40734. }
  40735. if (defines.COLORCURVES) {
  40736. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40737. }
  40738. };
  40739. /**
  40740. * Prepare the list of samplers associated with the Image Processing effects.
  40741. * @param uniformsList The list of uniforms used in the effect
  40742. * @param defines the list of defines currently in use
  40743. */
  40744. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40745. if (defines.COLORGRADING) {
  40746. samplersList.push("txColorTransform");
  40747. }
  40748. };
  40749. /**
  40750. * Prepare the list of defines associated to the shader.
  40751. * @param defines the list of defines to complete
  40752. */
  40753. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40754. if (forPostProcess === void 0) { forPostProcess = false; }
  40755. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40756. defines.VIGNETTE = false;
  40757. defines.TONEMAPPING = false;
  40758. defines.CONTRAST = false;
  40759. defines.EXPOSURE = false;
  40760. defines.COLORCURVES = false;
  40761. defines.COLORGRADING = false;
  40762. defines.COLORGRADING3D = false;
  40763. defines.IMAGEPROCESSING = false;
  40764. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40765. return;
  40766. }
  40767. defines.VIGNETTE = this.vignetteEnabled;
  40768. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40769. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40770. defines.TONEMAPPING = this.toneMappingEnabled;
  40771. defines.CONTRAST = (this.contrast !== 1.0);
  40772. defines.EXPOSURE = (this.exposure !== 1.0);
  40773. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40774. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40775. if (defines.COLORGRADING) {
  40776. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40777. }
  40778. else {
  40779. defines.COLORGRADING3D = false;
  40780. }
  40781. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40782. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40783. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40784. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40785. };
  40786. /**
  40787. * Returns true if all the image processing information are ready.
  40788. */
  40789. ImageProcessingConfiguration.prototype.isReady = function () {
  40790. // Color Grading texure can not be none blocking.
  40791. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40792. };
  40793. /**
  40794. * Binds the image processing to the shader.
  40795. * @param effect The effect to bind to
  40796. */
  40797. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40798. if (aspectRatio === void 0) { aspectRatio = 1; }
  40799. // Color Curves
  40800. if (this._colorCurvesEnabled && this.colorCurves) {
  40801. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40802. }
  40803. // Vignette
  40804. if (this._vignetteEnabled) {
  40805. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40806. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40807. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40808. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40809. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40810. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40811. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40812. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40813. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40814. var vignettePower = -2.0 * this.vignetteWeight;
  40815. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40816. }
  40817. // Exposure
  40818. effect.setFloat("exposureLinear", this.exposure);
  40819. // Contrast
  40820. effect.setFloat("contrast", this.contrast);
  40821. // Color transform settings
  40822. if (this.colorGradingTexture) {
  40823. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40824. var textureSize = this.colorGradingTexture.getSize().height;
  40825. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40826. 0.5 / textureSize, // textureOffset
  40827. textureSize, // textureSize
  40828. this.colorGradingTexture.level // weight
  40829. );
  40830. }
  40831. };
  40832. /**
  40833. * Clones the current image processing instance.
  40834. * @return The cloned image processing
  40835. */
  40836. ImageProcessingConfiguration.prototype.clone = function () {
  40837. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40838. };
  40839. /**
  40840. * Serializes the current image processing instance to a json representation.
  40841. * @return a JSON representation
  40842. */
  40843. ImageProcessingConfiguration.prototype.serialize = function () {
  40844. return BABYLON.SerializationHelper.Serialize(this);
  40845. };
  40846. /**
  40847. * Parses the image processing from a json representation.
  40848. * @param source the JSON source to parse
  40849. * @return The parsed image processing
  40850. */
  40851. ImageProcessingConfiguration.Parse = function (source) {
  40852. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40853. };
  40854. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40855. /**
  40856. * Used to apply the vignette as a mix with the pixel color.
  40857. */
  40858. get: function () {
  40859. return this._VIGNETTEMODE_MULTIPLY;
  40860. },
  40861. enumerable: true,
  40862. configurable: true
  40863. });
  40864. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40865. /**
  40866. * Used to apply the vignette as a replacement of the pixel color.
  40867. */
  40868. get: function () {
  40869. return this._VIGNETTEMODE_OPAQUE;
  40870. },
  40871. enumerable: true,
  40872. configurable: true
  40873. });
  40874. // Static constants associated to the image processing.
  40875. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40876. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40877. __decorate([
  40878. BABYLON.serializeAsColorCurves()
  40879. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40880. __decorate([
  40881. BABYLON.serialize()
  40882. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40883. __decorate([
  40884. BABYLON.serializeAsTexture()
  40885. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40886. __decorate([
  40887. BABYLON.serialize()
  40888. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40889. __decorate([
  40890. BABYLON.serialize()
  40891. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40892. __decorate([
  40893. BABYLON.serialize()
  40894. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40895. __decorate([
  40896. BABYLON.serialize()
  40897. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40898. __decorate([
  40899. BABYLON.serialize()
  40900. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40901. __decorate([
  40902. BABYLON.serialize()
  40903. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40904. __decorate([
  40905. BABYLON.serialize()
  40906. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40907. __decorate([
  40908. BABYLON.serialize()
  40909. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40910. __decorate([
  40911. BABYLON.serialize()
  40912. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40913. __decorate([
  40914. BABYLON.serialize()
  40915. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40916. __decorate([
  40917. BABYLON.serializeAsColor4()
  40918. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40919. __decorate([
  40920. BABYLON.serialize()
  40921. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40922. __decorate([
  40923. BABYLON.serialize()
  40924. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40925. __decorate([
  40926. BABYLON.serialize()
  40927. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40928. __decorate([
  40929. BABYLON.serialize()
  40930. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40931. __decorate([
  40932. BABYLON.serialize()
  40933. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40934. return ImageProcessingConfiguration;
  40935. }());
  40936. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40937. })(BABYLON || (BABYLON = {}));
  40938. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40939. "use strict";
  40940. var BABYLON;
  40941. (function (BABYLON) {
  40942. /**
  40943. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40944. * It can help converting any input color in a desired output one. This can then be used to create effects
  40945. * from sepia, black and white to sixties or futuristic rendering...
  40946. *
  40947. * The only supported format is currently 3dl.
  40948. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40949. */
  40950. var ColorGradingTexture = /** @class */ (function (_super) {
  40951. __extends(ColorGradingTexture, _super);
  40952. /**
  40953. * Instantiates a ColorGradingTexture from the following parameters.
  40954. *
  40955. * @param url The location of the color gradind data (currently only supporting 3dl)
  40956. * @param scene The scene the texture will be used in
  40957. */
  40958. function ColorGradingTexture(url, scene) {
  40959. var _this = _super.call(this, scene) || this;
  40960. if (!url) {
  40961. return _this;
  40962. }
  40963. _this._engine = scene.getEngine();
  40964. _this._textureMatrix = BABYLON.Matrix.Identity();
  40965. _this.name = url;
  40966. _this.url = url;
  40967. _this.hasAlpha = false;
  40968. _this.isCube = false;
  40969. _this.is3D = _this._engine.webGLVersion > 1;
  40970. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40971. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40972. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40973. _this.anisotropicFilteringLevel = 1;
  40974. _this._texture = _this._getFromCache(url, true);
  40975. if (!_this._texture) {
  40976. if (!scene.useDelayedTextureLoading) {
  40977. _this.loadTexture();
  40978. }
  40979. else {
  40980. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40981. }
  40982. }
  40983. return _this;
  40984. }
  40985. /**
  40986. * Returns the texture matrix used in most of the material.
  40987. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40988. */
  40989. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40990. return this._textureMatrix;
  40991. };
  40992. /**
  40993. * Occurs when the file being loaded is a .3dl LUT file.
  40994. */
  40995. ColorGradingTexture.prototype.load3dlTexture = function () {
  40996. var engine = this._engine;
  40997. var texture;
  40998. if (engine.webGLVersion === 1) {
  40999. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41000. }
  41001. else {
  41002. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41003. }
  41004. this._texture = texture;
  41005. var callback = function (text) {
  41006. if (typeof text !== "string") {
  41007. return;
  41008. }
  41009. var data = null;
  41010. var tempData = null;
  41011. var line;
  41012. var lines = text.split('\n');
  41013. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41014. var maxColor = 0;
  41015. for (var i = 0; i < lines.length; i++) {
  41016. line = lines[i];
  41017. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41018. continue;
  41019. if (line.indexOf('#') === 0)
  41020. continue;
  41021. var words = line.split(" ");
  41022. if (size === 0) {
  41023. // Number of space + one
  41024. size = words.length;
  41025. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41026. tempData = new Float32Array(size * size * size * 4);
  41027. continue;
  41028. }
  41029. if (size != 0) {
  41030. var r = Math.max(parseInt(words[0]), 0);
  41031. var g = Math.max(parseInt(words[1]), 0);
  41032. var b = Math.max(parseInt(words[2]), 0);
  41033. maxColor = Math.max(r, maxColor);
  41034. maxColor = Math.max(g, maxColor);
  41035. maxColor = Math.max(b, maxColor);
  41036. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41037. if (tempData) {
  41038. tempData[pixelStorageIndex + 0] = r;
  41039. tempData[pixelStorageIndex + 1] = g;
  41040. tempData[pixelStorageIndex + 2] = b;
  41041. }
  41042. pixelIndexSlice++;
  41043. if (pixelIndexSlice % size == 0) {
  41044. pixelIndexH++;
  41045. pixelIndexSlice = 0;
  41046. if (pixelIndexH % size == 0) {
  41047. pixelIndexW++;
  41048. pixelIndexH = 0;
  41049. }
  41050. }
  41051. }
  41052. }
  41053. if (tempData && data) {
  41054. for (var i = 0; i < tempData.length; i++) {
  41055. if (i > 0 && (i + 1) % 4 === 0) {
  41056. data[i] = 255;
  41057. }
  41058. else {
  41059. var value = tempData[i];
  41060. data[i] = (value / maxColor * 255);
  41061. }
  41062. }
  41063. }
  41064. if (texture.is3D) {
  41065. texture.updateSize(size, size, size);
  41066. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41067. }
  41068. else {
  41069. texture.updateSize(size * size, size);
  41070. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41071. }
  41072. };
  41073. var scene = this.getScene();
  41074. if (scene) {
  41075. scene._loadFile(this.url, callback);
  41076. }
  41077. else {
  41078. this._engine._loadFile(this.url, callback);
  41079. }
  41080. return this._texture;
  41081. };
  41082. /**
  41083. * Starts the loading process of the texture.
  41084. */
  41085. ColorGradingTexture.prototype.loadTexture = function () {
  41086. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41087. this.load3dlTexture();
  41088. }
  41089. };
  41090. /**
  41091. * Clones the color gradind texture.
  41092. */
  41093. ColorGradingTexture.prototype.clone = function () {
  41094. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41095. // Base texture
  41096. newTexture.level = this.level;
  41097. return newTexture;
  41098. };
  41099. /**
  41100. * Called during delayed load for textures.
  41101. */
  41102. ColorGradingTexture.prototype.delayLoad = function () {
  41103. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41104. return;
  41105. }
  41106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41107. this._texture = this._getFromCache(this.url, true);
  41108. if (!this._texture) {
  41109. this.loadTexture();
  41110. }
  41111. };
  41112. /**
  41113. * Parses a color grading texture serialized by Babylon.
  41114. * @param parsedTexture The texture information being parsedTexture
  41115. * @param scene The scene to load the texture in
  41116. * @param rootUrl The root url of the data assets to load
  41117. * @return A color gradind texture
  41118. */
  41119. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41120. var texture = null;
  41121. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41122. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41123. texture.name = parsedTexture.name;
  41124. texture.level = parsedTexture.level;
  41125. }
  41126. return texture;
  41127. };
  41128. /**
  41129. * Serializes the LUT texture to json format.
  41130. */
  41131. ColorGradingTexture.prototype.serialize = function () {
  41132. if (!this.name) {
  41133. return null;
  41134. }
  41135. var serializationObject = {};
  41136. serializationObject.name = this.name;
  41137. serializationObject.level = this.level;
  41138. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41139. return serializationObject;
  41140. };
  41141. /**
  41142. * Empty line regex stored for GC.
  41143. */
  41144. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41145. return ColorGradingTexture;
  41146. }(BABYLON.BaseTexture));
  41147. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41148. })(BABYLON || (BABYLON = {}));
  41149. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41150. "use strict";
  41151. var BABYLON;
  41152. (function (BABYLON) {
  41153. /**
  41154. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41155. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41156. * 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;
  41157. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41158. */
  41159. var ColorCurves = /** @class */ (function () {
  41160. function ColorCurves() {
  41161. this._dirty = true;
  41162. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41163. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41164. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41165. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41166. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41167. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41168. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41169. this._globalHue = 30;
  41170. this._globalDensity = 0;
  41171. this._globalSaturation = 0;
  41172. this._globalExposure = 0;
  41173. this._highlightsHue = 30;
  41174. this._highlightsDensity = 0;
  41175. this._highlightsSaturation = 0;
  41176. this._highlightsExposure = 0;
  41177. this._midtonesHue = 30;
  41178. this._midtonesDensity = 0;
  41179. this._midtonesSaturation = 0;
  41180. this._midtonesExposure = 0;
  41181. this._shadowsHue = 30;
  41182. this._shadowsDensity = 0;
  41183. this._shadowsSaturation = 0;
  41184. this._shadowsExposure = 0;
  41185. }
  41186. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41187. /**
  41188. * Gets the global Hue value.
  41189. * 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).
  41190. */
  41191. get: function () {
  41192. return this._globalHue;
  41193. },
  41194. /**
  41195. * Sets the global Hue value.
  41196. * 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).
  41197. */
  41198. set: function (value) {
  41199. this._globalHue = value;
  41200. this._dirty = true;
  41201. },
  41202. enumerable: true,
  41203. configurable: true
  41204. });
  41205. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41206. /**
  41207. * Gets the global Density value.
  41208. * 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.
  41209. * Values less than zero provide a filter of opposite hue.
  41210. */
  41211. get: function () {
  41212. return this._globalDensity;
  41213. },
  41214. /**
  41215. * Sets the global Density value.
  41216. * 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.
  41217. * Values less than zero provide a filter of opposite hue.
  41218. */
  41219. set: function (value) {
  41220. this._globalDensity = value;
  41221. this._dirty = true;
  41222. },
  41223. enumerable: true,
  41224. configurable: true
  41225. });
  41226. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41227. /**
  41228. * Gets the global Saturation value.
  41229. * 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.
  41230. */
  41231. get: function () {
  41232. return this._globalSaturation;
  41233. },
  41234. /**
  41235. * Sets the global Saturation value.
  41236. * 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.
  41237. */
  41238. set: function (value) {
  41239. this._globalSaturation = value;
  41240. this._dirty = true;
  41241. },
  41242. enumerable: true,
  41243. configurable: true
  41244. });
  41245. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41246. /**
  41247. * Gets the highlights Hue value.
  41248. * 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).
  41249. */
  41250. get: function () {
  41251. return this._highlightsHue;
  41252. },
  41253. /**
  41254. * Sets the highlights Hue value.
  41255. * 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).
  41256. */
  41257. set: function (value) {
  41258. this._highlightsHue = value;
  41259. this._dirty = true;
  41260. },
  41261. enumerable: true,
  41262. configurable: true
  41263. });
  41264. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41265. /**
  41266. * Gets the highlights Density value.
  41267. * 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.
  41268. * Values less than zero provide a filter of opposite hue.
  41269. */
  41270. get: function () {
  41271. return this._highlightsDensity;
  41272. },
  41273. /**
  41274. * Sets the highlights Density value.
  41275. * 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.
  41276. * Values less than zero provide a filter of opposite hue.
  41277. */
  41278. set: function (value) {
  41279. this._highlightsDensity = value;
  41280. this._dirty = true;
  41281. },
  41282. enumerable: true,
  41283. configurable: true
  41284. });
  41285. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41286. /**
  41287. * Gets the highlights Saturation value.
  41288. * 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.
  41289. */
  41290. get: function () {
  41291. return this._highlightsSaturation;
  41292. },
  41293. /**
  41294. * Sets the highlights Saturation value.
  41295. * 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.
  41296. */
  41297. set: function (value) {
  41298. this._highlightsSaturation = value;
  41299. this._dirty = true;
  41300. },
  41301. enumerable: true,
  41302. configurable: true
  41303. });
  41304. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41305. /**
  41306. * Gets the highlights Exposure value.
  41307. * 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.
  41308. */
  41309. get: function () {
  41310. return this._highlightsExposure;
  41311. },
  41312. /**
  41313. * Sets the highlights Exposure value.
  41314. * 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.
  41315. */
  41316. set: function (value) {
  41317. this._highlightsExposure = value;
  41318. this._dirty = true;
  41319. },
  41320. enumerable: true,
  41321. configurable: true
  41322. });
  41323. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41324. /**
  41325. * Gets the midtones Hue value.
  41326. * 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).
  41327. */
  41328. get: function () {
  41329. return this._midtonesHue;
  41330. },
  41331. /**
  41332. * Sets the midtones Hue value.
  41333. * 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).
  41334. */
  41335. set: function (value) {
  41336. this._midtonesHue = value;
  41337. this._dirty = true;
  41338. },
  41339. enumerable: true,
  41340. configurable: true
  41341. });
  41342. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41343. /**
  41344. * Gets the midtones Density value.
  41345. * 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.
  41346. * Values less than zero provide a filter of opposite hue.
  41347. */
  41348. get: function () {
  41349. return this._midtonesDensity;
  41350. },
  41351. /**
  41352. * Sets the midtones Density value.
  41353. * 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.
  41354. * Values less than zero provide a filter of opposite hue.
  41355. */
  41356. set: function (value) {
  41357. this._midtonesDensity = value;
  41358. this._dirty = true;
  41359. },
  41360. enumerable: true,
  41361. configurable: true
  41362. });
  41363. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41364. /**
  41365. * Gets the midtones Saturation value.
  41366. * 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.
  41367. */
  41368. get: function () {
  41369. return this._midtonesSaturation;
  41370. },
  41371. /**
  41372. * Sets the midtones Saturation value.
  41373. * 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.
  41374. */
  41375. set: function (value) {
  41376. this._midtonesSaturation = value;
  41377. this._dirty = true;
  41378. },
  41379. enumerable: true,
  41380. configurable: true
  41381. });
  41382. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41383. /**
  41384. * Gets the midtones Exposure value.
  41385. * 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.
  41386. */
  41387. get: function () {
  41388. return this._midtonesExposure;
  41389. },
  41390. /**
  41391. * Sets the midtones Exposure value.
  41392. * 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.
  41393. */
  41394. set: function (value) {
  41395. this._midtonesExposure = value;
  41396. this._dirty = true;
  41397. },
  41398. enumerable: true,
  41399. configurable: true
  41400. });
  41401. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41402. /**
  41403. * Gets the shadows Hue value.
  41404. * 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).
  41405. */
  41406. get: function () {
  41407. return this._shadowsHue;
  41408. },
  41409. /**
  41410. * Sets the shadows Hue value.
  41411. * 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).
  41412. */
  41413. set: function (value) {
  41414. this._shadowsHue = value;
  41415. this._dirty = true;
  41416. },
  41417. enumerable: true,
  41418. configurable: true
  41419. });
  41420. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41421. /**
  41422. * Gets the shadows Density value.
  41423. * 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.
  41424. * Values less than zero provide a filter of opposite hue.
  41425. */
  41426. get: function () {
  41427. return this._shadowsDensity;
  41428. },
  41429. /**
  41430. * Sets the shadows Density value.
  41431. * 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.
  41432. * Values less than zero provide a filter of opposite hue.
  41433. */
  41434. set: function (value) {
  41435. this._shadowsDensity = value;
  41436. this._dirty = true;
  41437. },
  41438. enumerable: true,
  41439. configurable: true
  41440. });
  41441. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41442. /**
  41443. * Gets the shadows Saturation value.
  41444. * 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.
  41445. */
  41446. get: function () {
  41447. return this._shadowsSaturation;
  41448. },
  41449. /**
  41450. * Sets the shadows Saturation value.
  41451. * 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.
  41452. */
  41453. set: function (value) {
  41454. this._shadowsSaturation = value;
  41455. this._dirty = true;
  41456. },
  41457. enumerable: true,
  41458. configurable: true
  41459. });
  41460. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41461. /**
  41462. * Gets the shadows Exposure value.
  41463. * 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.
  41464. */
  41465. get: function () {
  41466. return this._shadowsExposure;
  41467. },
  41468. /**
  41469. * Sets the shadows Exposure value.
  41470. * 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.
  41471. */
  41472. set: function (value) {
  41473. this._shadowsExposure = value;
  41474. this._dirty = true;
  41475. },
  41476. enumerable: true,
  41477. configurable: true
  41478. });
  41479. ColorCurves.prototype.getClassName = function () {
  41480. return "ColorCurves";
  41481. };
  41482. /**
  41483. * Binds the color curves to the shader.
  41484. * @param colorCurves The color curve to bind
  41485. * @param effect The effect to bind to
  41486. */
  41487. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41488. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41489. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41490. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41491. if (colorCurves._dirty) {
  41492. colorCurves._dirty = false;
  41493. // Fill in global info.
  41494. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41495. // Compute highlights info.
  41496. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41497. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41498. // Compute midtones info.
  41499. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41500. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41501. // Compute shadows info.
  41502. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41503. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41504. // Compute deltas (neutral is midtones).
  41505. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41506. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41507. }
  41508. if (effect) {
  41509. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41510. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41511. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41512. }
  41513. };
  41514. /**
  41515. * Prepare the list of uniforms associated with the ColorCurves effects.
  41516. * @param uniformsList The list of uniforms used in the effect
  41517. */
  41518. ColorCurves.PrepareUniforms = function (uniformsList) {
  41519. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41520. };
  41521. /**
  41522. * Returns color grading data based on a hue, density, saturation and exposure value.
  41523. * @param filterHue The hue of the color filter.
  41524. * @param filterDensity The density of the color filter.
  41525. * @param saturation The saturation.
  41526. * @param exposure The exposure.
  41527. * @param result The result data container.
  41528. */
  41529. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41530. if (hue == null) {
  41531. return;
  41532. }
  41533. hue = ColorCurves.clamp(hue, 0, 360);
  41534. density = ColorCurves.clamp(density, -100, 100);
  41535. saturation = ColorCurves.clamp(saturation, -100, 100);
  41536. exposure = ColorCurves.clamp(exposure, -100, 100);
  41537. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41538. // so that the maximum filter density is only 50% control. This provides fine control
  41539. // for small values and reasonable range.
  41540. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41541. density *= 0.5;
  41542. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41543. if (density < 0) {
  41544. density *= -1;
  41545. hue = (hue + 180) % 360;
  41546. }
  41547. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41548. result.scaleToRef(2, result);
  41549. result.a = 1 + 0.01 * saturation;
  41550. };
  41551. /**
  41552. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41553. * @param value The input slider value in range [-100,100].
  41554. * @returns Adjusted value.
  41555. */
  41556. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41557. value /= 100;
  41558. var x = Math.abs(value);
  41559. x = Math.pow(x, 2);
  41560. if (value < 0) {
  41561. x *= -1;
  41562. }
  41563. x *= 100;
  41564. return x;
  41565. };
  41566. /**
  41567. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41568. * @param hue The hue (H) input.
  41569. * @param saturation The saturation (S) input.
  41570. * @param brightness The brightness (B) input.
  41571. * @result An RGBA color represented as Vector4.
  41572. */
  41573. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41574. var h = ColorCurves.clamp(hue, 0, 360);
  41575. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41576. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41577. if (s === 0) {
  41578. result.r = v;
  41579. result.g = v;
  41580. result.b = v;
  41581. }
  41582. else {
  41583. // sector 0 to 5
  41584. h /= 60;
  41585. var i = Math.floor(h);
  41586. // fractional part of h
  41587. var f = h - i;
  41588. var p = v * (1 - s);
  41589. var q = v * (1 - s * f);
  41590. var t = v * (1 - s * (1 - f));
  41591. switch (i) {
  41592. case 0:
  41593. result.r = v;
  41594. result.g = t;
  41595. result.b = p;
  41596. break;
  41597. case 1:
  41598. result.r = q;
  41599. result.g = v;
  41600. result.b = p;
  41601. break;
  41602. case 2:
  41603. result.r = p;
  41604. result.g = v;
  41605. result.b = t;
  41606. break;
  41607. case 3:
  41608. result.r = p;
  41609. result.g = q;
  41610. result.b = v;
  41611. break;
  41612. case 4:
  41613. result.r = t;
  41614. result.g = p;
  41615. result.b = v;
  41616. break;
  41617. default:// case 5:
  41618. result.r = v;
  41619. result.g = p;
  41620. result.b = q;
  41621. break;
  41622. }
  41623. }
  41624. result.a = 1;
  41625. };
  41626. /**
  41627. * Returns a value clamped between min and max
  41628. * @param value The value to clamp
  41629. * @param min The minimum of value
  41630. * @param max The maximum of value
  41631. * @returns The clamped value.
  41632. */
  41633. ColorCurves.clamp = function (value, min, max) {
  41634. return Math.min(Math.max(value, min), max);
  41635. };
  41636. /**
  41637. * Clones the current color curve instance.
  41638. * @return The cloned curves
  41639. */
  41640. ColorCurves.prototype.clone = function () {
  41641. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41642. };
  41643. /**
  41644. * Serializes the current color curve instance to a json representation.
  41645. * @return a JSON representation
  41646. */
  41647. ColorCurves.prototype.serialize = function () {
  41648. return BABYLON.SerializationHelper.Serialize(this);
  41649. };
  41650. /**
  41651. * Parses the color curve from a json representation.
  41652. * @param source the JSON source to parse
  41653. * @return The parsed curves
  41654. */
  41655. ColorCurves.Parse = function (source) {
  41656. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41657. };
  41658. __decorate([
  41659. BABYLON.serialize()
  41660. ], ColorCurves.prototype, "_globalHue", void 0);
  41661. __decorate([
  41662. BABYLON.serialize()
  41663. ], ColorCurves.prototype, "_globalDensity", void 0);
  41664. __decorate([
  41665. BABYLON.serialize()
  41666. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41667. __decorate([
  41668. BABYLON.serialize()
  41669. ], ColorCurves.prototype, "_globalExposure", void 0);
  41670. __decorate([
  41671. BABYLON.serialize()
  41672. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41673. __decorate([
  41674. BABYLON.serialize()
  41675. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41676. __decorate([
  41677. BABYLON.serialize()
  41678. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41679. __decorate([
  41680. BABYLON.serialize()
  41681. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41682. __decorate([
  41683. BABYLON.serialize()
  41684. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41685. __decorate([
  41686. BABYLON.serialize()
  41687. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41688. __decorate([
  41689. BABYLON.serialize()
  41690. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41691. __decorate([
  41692. BABYLON.serialize()
  41693. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41694. return ColorCurves;
  41695. }());
  41696. BABYLON.ColorCurves = ColorCurves;
  41697. })(BABYLON || (BABYLON = {}));
  41698. //# sourceMappingURL=babylon.colorCurves.js.map
  41699. "use strict";
  41700. //# sourceMappingURL=babylon.behavior.js.map
  41701. "use strict";
  41702. var BABYLON;
  41703. (function (BABYLON) {
  41704. /**
  41705. * "Static Class" containing the most commonly used helper while dealing with material for
  41706. * rendering purpose.
  41707. *
  41708. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41709. *
  41710. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41711. */
  41712. var MaterialHelper = /** @class */ (function () {
  41713. function MaterialHelper() {
  41714. }
  41715. /**
  41716. * Bind the current view position to an effect.
  41717. * @param effect The effect to be bound
  41718. * @param scene The scene the eyes position is used from
  41719. */
  41720. MaterialHelper.BindEyePosition = function (effect, scene) {
  41721. if (scene._forcedViewPosition) {
  41722. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41723. return;
  41724. }
  41725. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41726. };
  41727. /**
  41728. * Helps preparing the defines values about the UVs in used in the effect.
  41729. * UVs are shared as much as we can accross chanels in the shaders.
  41730. * @param texture The texture we are preparing the UVs for
  41731. * @param defines The defines to update
  41732. * @param key The chanel key "diffuse", "specular"... used in the shader
  41733. */
  41734. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41735. defines._needUVs = true;
  41736. defines[key] = true;
  41737. if (texture.getTextureMatrix().isIdentity(true)) {
  41738. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41739. if (texture.coordinatesIndex === 0) {
  41740. defines["MAINUV1"] = true;
  41741. }
  41742. else {
  41743. defines["MAINUV2"] = true;
  41744. }
  41745. }
  41746. else {
  41747. defines[key + "DIRECTUV"] = 0;
  41748. }
  41749. };
  41750. /**
  41751. * Binds a texture matrix value to its corrsponding uniform
  41752. * @param texture The texture to bind the matrix for
  41753. * @param uniformBuffer The uniform buffer receivin the data
  41754. * @param key The chanel key "diffuse", "specular"... used in the shader
  41755. */
  41756. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41757. var matrix = texture.getTextureMatrix();
  41758. if (!matrix.isIdentity(true)) {
  41759. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41760. }
  41761. };
  41762. /**
  41763. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41764. * @param mesh defines the current mesh
  41765. * @param scene defines the current scene
  41766. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41767. * @param pointsCloud defines if point cloud rendering has to be turned on
  41768. * @param fogEnabled defines if fog has to be turned on
  41769. * @param alphaTest defines if alpha testing has to be turned on
  41770. * @param defines defines the current list of defines
  41771. */
  41772. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41773. if (defines._areMiscDirty) {
  41774. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41775. defines["POINTSIZE"] = pointsCloud;
  41776. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41777. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41778. defines["ALPHATEST"] = alphaTest;
  41779. }
  41780. };
  41781. /**
  41782. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41783. * @param scene defines the current scene
  41784. * @param engine defines the current engine
  41785. * @param defines specifies the list of active defines
  41786. * @param useInstances defines if instances have to be turned on
  41787. * @param useClipPlane defines if clip plane have to be turned on
  41788. */
  41789. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41790. if (useClipPlane === void 0) { useClipPlane = null; }
  41791. var changed = false;
  41792. if (useClipPlane == null) {
  41793. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41794. }
  41795. if (defines["CLIPPLANE"] !== useClipPlane) {
  41796. defines["CLIPPLANE"] = useClipPlane;
  41797. changed = true;
  41798. }
  41799. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41800. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41801. changed = true;
  41802. }
  41803. if (defines["INSTANCES"] !== useInstances) {
  41804. defines["INSTANCES"] = useInstances;
  41805. changed = true;
  41806. }
  41807. if (changed) {
  41808. defines.markAsUnprocessed();
  41809. }
  41810. };
  41811. /**
  41812. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41813. * @param mesh The mesh containing the geometry data we will draw
  41814. * @param defines The defines to update
  41815. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41816. * @param useBones Precise whether bones should be used or not (override mesh info)
  41817. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41818. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41819. * @returns false if defines are considered not dirty and have not been checked
  41820. */
  41821. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41822. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41823. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41824. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41825. return false;
  41826. }
  41827. defines._normals = defines._needNormals;
  41828. defines._uvs = defines._needUVs;
  41829. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41830. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41831. defines["TANGENT"] = true;
  41832. }
  41833. if (defines._needUVs) {
  41834. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41835. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41836. }
  41837. else {
  41838. defines["UV1"] = false;
  41839. defines["UV2"] = false;
  41840. }
  41841. if (useVertexColor) {
  41842. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41843. defines["VERTEXCOLOR"] = hasVertexColors;
  41844. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41845. }
  41846. if (useBones) {
  41847. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41848. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41849. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41850. }
  41851. else {
  41852. defines["NUM_BONE_INFLUENCERS"] = 0;
  41853. defines["BonesPerMesh"] = 0;
  41854. }
  41855. }
  41856. if (useMorphTargets) {
  41857. var manager = mesh.morphTargetManager;
  41858. if (manager) {
  41859. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41860. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41861. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41862. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41863. }
  41864. else {
  41865. defines["MORPHTARGETS_TANGENT"] = false;
  41866. defines["MORPHTARGETS_NORMAL"] = false;
  41867. defines["MORPHTARGETS"] = false;
  41868. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41869. }
  41870. }
  41871. return true;
  41872. };
  41873. /**
  41874. * Prepares the defines related to the light information passed in parameter
  41875. * @param scene The scene we are intending to draw
  41876. * @param mesh The mesh the effect is compiling for
  41877. * @param defines The defines to update
  41878. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41879. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41880. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41881. * @returns true if normals will be required for the rest of the effect
  41882. */
  41883. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41884. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41885. if (disableLighting === void 0) { disableLighting = false; }
  41886. if (!defines._areLightsDirty) {
  41887. return defines._needNormals;
  41888. }
  41889. var lightIndex = 0;
  41890. var needNormals = false;
  41891. var needRebuild = false;
  41892. var lightmapMode = false;
  41893. var shadowEnabled = false;
  41894. var specularEnabled = false;
  41895. if (scene.lightsEnabled && !disableLighting) {
  41896. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41897. var light = _a[_i];
  41898. needNormals = true;
  41899. if (defines["LIGHT" + lightIndex] === undefined) {
  41900. needRebuild = true;
  41901. }
  41902. defines["LIGHT" + lightIndex] = true;
  41903. defines["SPOTLIGHT" + lightIndex] = false;
  41904. defines["HEMILIGHT" + lightIndex] = false;
  41905. defines["POINTLIGHT" + lightIndex] = false;
  41906. defines["DIRLIGHT" + lightIndex] = false;
  41907. var type;
  41908. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41909. type = "SPOTLIGHT" + lightIndex;
  41910. var spotLight = light;
  41911. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41912. }
  41913. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41914. type = "HEMILIGHT" + lightIndex;
  41915. }
  41916. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41917. type = "POINTLIGHT" + lightIndex;
  41918. }
  41919. else {
  41920. type = "DIRLIGHT" + lightIndex;
  41921. }
  41922. defines[type] = true;
  41923. // Specular
  41924. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41925. specularEnabled = true;
  41926. }
  41927. // Shadows
  41928. defines["SHADOW" + lightIndex] = false;
  41929. defines["SHADOWPCF" + lightIndex] = false;
  41930. defines["SHADOWPCSS" + lightIndex] = false;
  41931. defines["SHADOWPOISSON" + lightIndex] = false;
  41932. defines["SHADOWESM" + lightIndex] = false;
  41933. defines["SHADOWCUBE" + lightIndex] = false;
  41934. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41935. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41936. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41937. var shadowGenerator = light.getShadowGenerator();
  41938. if (shadowGenerator) {
  41939. shadowEnabled = true;
  41940. shadowGenerator.prepareDefines(defines, lightIndex);
  41941. }
  41942. }
  41943. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41944. lightmapMode = true;
  41945. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41946. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41947. }
  41948. else {
  41949. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41950. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41951. }
  41952. lightIndex++;
  41953. if (lightIndex === maxSimultaneousLights)
  41954. break;
  41955. }
  41956. }
  41957. defines["SPECULARTERM"] = specularEnabled;
  41958. defines["SHADOWS"] = shadowEnabled;
  41959. // Resetting all other lights if any
  41960. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41961. if (defines["LIGHT" + index] !== undefined) {
  41962. defines["LIGHT" + index] = false;
  41963. defines["HEMILIGHT" + lightIndex] = false;
  41964. defines["POINTLIGHT" + lightIndex] = false;
  41965. defines["DIRLIGHT" + lightIndex] = false;
  41966. defines["SPOTLIGHT" + lightIndex] = false;
  41967. defines["SHADOW" + lightIndex] = false;
  41968. }
  41969. }
  41970. var caps = scene.getEngine().getCaps();
  41971. if (defines["SHADOWFLOAT"] === undefined) {
  41972. needRebuild = true;
  41973. }
  41974. defines["SHADOWFLOAT"] = shadowEnabled &&
  41975. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41976. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41977. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41978. if (needRebuild) {
  41979. defines.rebuild();
  41980. }
  41981. return needNormals;
  41982. };
  41983. /**
  41984. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41985. * that won t be acctive due to defines being turned off.
  41986. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41987. * @param samplersList The samplers list
  41988. * @param defines The defines helping in the list generation
  41989. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41990. */
  41991. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41992. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41993. var uniformsList;
  41994. var uniformBuffersList = null;
  41995. if (uniformsListOrOptions.uniformsNames) {
  41996. var options = uniformsListOrOptions;
  41997. uniformsList = options.uniformsNames;
  41998. uniformBuffersList = options.uniformBuffersNames;
  41999. samplersList = options.samplers;
  42000. defines = options.defines;
  42001. maxSimultaneousLights = options.maxSimultaneousLights;
  42002. }
  42003. else {
  42004. uniformsList = uniformsListOrOptions;
  42005. if (!samplersList) {
  42006. samplersList = [];
  42007. }
  42008. }
  42009. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42010. if (!defines["LIGHT" + lightIndex]) {
  42011. break;
  42012. }
  42013. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42014. if (uniformBuffersList) {
  42015. uniformBuffersList.push("Light" + lightIndex);
  42016. }
  42017. samplersList.push("shadowSampler" + lightIndex);
  42018. samplersList.push("depthSampler" + lightIndex);
  42019. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42020. samplersList.push("projectionLightSampler" + lightIndex);
  42021. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42022. }
  42023. }
  42024. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42025. uniformsList.push("morphTargetInfluences");
  42026. }
  42027. };
  42028. /**
  42029. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42030. * @param defines The defines to update while falling back
  42031. * @param fallbacks The authorized effect fallbacks
  42032. * @param maxSimultaneousLights The maximum number of lights allowed
  42033. * @param rank the current rank of the Effect
  42034. * @returns The newly affected rank
  42035. */
  42036. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42037. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42038. if (rank === void 0) { rank = 0; }
  42039. var lightFallbackRank = 0;
  42040. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42041. if (!defines["LIGHT" + lightIndex]) {
  42042. break;
  42043. }
  42044. if (lightIndex > 0) {
  42045. lightFallbackRank = rank + lightIndex;
  42046. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42047. }
  42048. if (!defines["SHADOWS"]) {
  42049. if (defines["SHADOW" + lightIndex]) {
  42050. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42051. }
  42052. if (defines["SHADOWPCF" + lightIndex]) {
  42053. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42054. }
  42055. if (defines["SHADOWPCSS" + lightIndex]) {
  42056. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42057. }
  42058. if (defines["SHADOWPOISSON" + lightIndex]) {
  42059. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42060. }
  42061. if (defines["SHADOWESM" + lightIndex]) {
  42062. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42063. }
  42064. }
  42065. }
  42066. return lightFallbackRank++;
  42067. };
  42068. /**
  42069. * Prepares the list of attributes required for morph targets according to the effect defines.
  42070. * @param attribs The current list of supported attribs
  42071. * @param mesh The mesh to prepare the morph targets attributes for
  42072. * @param defines The current Defines of the effect
  42073. */
  42074. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42075. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42076. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42077. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42078. var manager = mesh.morphTargetManager;
  42079. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42080. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42081. for (var index = 0; index < influencers; index++) {
  42082. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42083. if (normal) {
  42084. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42085. }
  42086. if (tangent) {
  42087. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42088. }
  42089. if (attribs.length > maxAttributesCount) {
  42090. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42091. }
  42092. }
  42093. }
  42094. };
  42095. /**
  42096. * Prepares the list of attributes required for bones according to the effect defines.
  42097. * @param attribs The current list of supported attribs
  42098. * @param mesh The mesh to prepare the bones attributes for
  42099. * @param defines The current Defines of the effect
  42100. * @param fallbacks The current efffect fallback strategy
  42101. */
  42102. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42103. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42104. fallbacks.addCPUSkinningFallback(0, mesh);
  42105. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42106. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42107. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42110. }
  42111. }
  42112. };
  42113. /**
  42114. * Prepares the list of attributes required for instances according to the effect defines.
  42115. * @param attribs The current list of supported attribs
  42116. * @param defines The current Defines of the effect
  42117. */
  42118. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42119. if (defines["INSTANCES"]) {
  42120. attribs.push("world0");
  42121. attribs.push("world1");
  42122. attribs.push("world2");
  42123. attribs.push("world3");
  42124. }
  42125. };
  42126. /**
  42127. * Binds the light shadow information to the effect for the given mesh.
  42128. * @param light The light containing the generator
  42129. * @param scene The scene the lights belongs to
  42130. * @param mesh The mesh we are binding the information to render
  42131. * @param lightIndex The light index in the effect used to render the mesh
  42132. * @param effect The effect we are binding the data to
  42133. */
  42134. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42135. if (light.shadowEnabled && mesh.receiveShadows) {
  42136. var shadowGenerator = light.getShadowGenerator();
  42137. if (shadowGenerator) {
  42138. shadowGenerator.bindShadowLight(lightIndex, effect);
  42139. }
  42140. }
  42141. };
  42142. /**
  42143. * Binds the light information to the effect.
  42144. * @param light The light containing the generator
  42145. * @param effect The effect we are binding the data to
  42146. * @param lightIndex The light index in the effect used to render
  42147. */
  42148. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42149. light.transferToEffect(effect, lightIndex + "");
  42150. };
  42151. /**
  42152. * Binds the lights information from the scene to the effect for the given mesh.
  42153. * @param scene The scene the lights belongs to
  42154. * @param mesh The mesh we are binding the information to render
  42155. * @param effect The effect we are binding the data to
  42156. * @param defines The generated defines for the effect
  42157. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42158. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42159. */
  42160. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42161. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42162. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42163. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42164. for (var i = 0; i < len; i++) {
  42165. var light = mesh._lightSources[i];
  42166. var iAsString = i.toString();
  42167. var scaledIntensity = light.getScaledIntensity();
  42168. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42169. MaterialHelper.BindLightProperties(light, effect, i);
  42170. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42171. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42172. if (defines["SPECULARTERM"]) {
  42173. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42174. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42175. }
  42176. // Shadows
  42177. if (scene.shadowsEnabled) {
  42178. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42179. }
  42180. light._uniformBuffer.update();
  42181. }
  42182. };
  42183. /**
  42184. * Binds the fog information from the scene to the effect for the given mesh.
  42185. * @param scene The scene the lights belongs to
  42186. * @param mesh The mesh we are binding the information to render
  42187. * @param effect The effect we are binding the data to
  42188. */
  42189. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42190. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42191. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42192. effect.setColor3("vFogColor", scene.fogColor);
  42193. }
  42194. };
  42195. /**
  42196. * Binds the bones information from the mesh to the effect.
  42197. * @param mesh The mesh we are binding the information to render
  42198. * @param effect The effect we are binding the data to
  42199. */
  42200. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42201. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42202. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42203. if (matrices && effect) {
  42204. effect.setMatrices("mBones", matrices);
  42205. }
  42206. }
  42207. };
  42208. /**
  42209. * Binds the morph targets information from the mesh to the effect.
  42210. * @param abstractMesh The mesh we are binding the information to render
  42211. * @param effect The effect we are binding the data to
  42212. */
  42213. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42214. var manager = abstractMesh.morphTargetManager;
  42215. if (!abstractMesh || !manager) {
  42216. return;
  42217. }
  42218. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42219. };
  42220. /**
  42221. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42222. * @param defines The generated defines used in the effect
  42223. * @param effect The effect we are binding the data to
  42224. * @param scene The scene we are willing to render with logarithmic scale for
  42225. */
  42226. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42227. if (defines["LOGARITHMICDEPTH"]) {
  42228. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42229. }
  42230. };
  42231. /**
  42232. * Binds the clip plane information from the scene to the effect.
  42233. * @param scene The scene the clip plane information are extracted from
  42234. * @param effect The effect we are binding the data to
  42235. */
  42236. MaterialHelper.BindClipPlane = function (effect, scene) {
  42237. if (scene.clipPlane) {
  42238. var clipPlane = scene.clipPlane;
  42239. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42240. }
  42241. };
  42242. return MaterialHelper;
  42243. }());
  42244. BABYLON.MaterialHelper = MaterialHelper;
  42245. })(BABYLON || (BABYLON = {}));
  42246. //# sourceMappingURL=babylon.materialHelper.js.map
  42247. "use strict";
  42248. var BABYLON;
  42249. (function (BABYLON) {
  42250. var PushMaterial = /** @class */ (function (_super) {
  42251. __extends(PushMaterial, _super);
  42252. function PushMaterial(name, scene) {
  42253. var _this = _super.call(this, name, scene) || this;
  42254. _this._normalMatrix = new BABYLON.Matrix();
  42255. _this.storeEffectOnSubMeshes = true;
  42256. return _this;
  42257. }
  42258. PushMaterial.prototype.getEffect = function () {
  42259. return this._activeEffect;
  42260. };
  42261. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42262. if (!mesh) {
  42263. return false;
  42264. }
  42265. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42266. return true;
  42267. }
  42268. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42269. };
  42270. /**
  42271. * Binds the given world matrix to the active effect
  42272. *
  42273. * @param world the matrix to bind
  42274. */
  42275. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42276. this._activeEffect.setMatrix("world", world);
  42277. };
  42278. /**
  42279. * Binds the given normal matrix to the active effect
  42280. *
  42281. * @param normalMatrix the matrix to bind
  42282. */
  42283. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42284. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42285. };
  42286. PushMaterial.prototype.bind = function (world, mesh) {
  42287. if (!mesh) {
  42288. return;
  42289. }
  42290. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42291. };
  42292. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42293. if (effect === void 0) { effect = null; }
  42294. _super.prototype._afterBind.call(this, mesh);
  42295. this.getScene()._cachedEffect = effect;
  42296. };
  42297. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42298. if (visibility === void 0) { visibility = 1; }
  42299. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42300. };
  42301. return PushMaterial;
  42302. }(BABYLON.Material));
  42303. BABYLON.PushMaterial = PushMaterial;
  42304. })(BABYLON || (BABYLON = {}));
  42305. //# sourceMappingURL=babylon.pushMaterial.js.map
  42306. "use strict";
  42307. var BABYLON;
  42308. (function (BABYLON) {
  42309. /** @ignore */
  42310. var StandardMaterialDefines = /** @class */ (function (_super) {
  42311. __extends(StandardMaterialDefines, _super);
  42312. function StandardMaterialDefines() {
  42313. var _this = _super.call(this) || this;
  42314. _this.MAINUV1 = false;
  42315. _this.MAINUV2 = false;
  42316. _this.DIFFUSE = false;
  42317. _this.DIFFUSEDIRECTUV = 0;
  42318. _this.AMBIENT = false;
  42319. _this.AMBIENTDIRECTUV = 0;
  42320. _this.OPACITY = false;
  42321. _this.OPACITYDIRECTUV = 0;
  42322. _this.OPACITYRGB = false;
  42323. _this.REFLECTION = false;
  42324. _this.EMISSIVE = false;
  42325. _this.EMISSIVEDIRECTUV = 0;
  42326. _this.SPECULAR = false;
  42327. _this.SPECULARDIRECTUV = 0;
  42328. _this.BUMP = false;
  42329. _this.BUMPDIRECTUV = 0;
  42330. _this.PARALLAX = false;
  42331. _this.PARALLAXOCCLUSION = false;
  42332. _this.SPECULAROVERALPHA = false;
  42333. _this.CLIPPLANE = false;
  42334. _this.ALPHATEST = false;
  42335. _this.DEPTHPREPASS = false;
  42336. _this.ALPHAFROMDIFFUSE = false;
  42337. _this.POINTSIZE = false;
  42338. _this.FOG = false;
  42339. _this.SPECULARTERM = false;
  42340. _this.DIFFUSEFRESNEL = false;
  42341. _this.OPACITYFRESNEL = false;
  42342. _this.REFLECTIONFRESNEL = false;
  42343. _this.REFRACTIONFRESNEL = false;
  42344. _this.EMISSIVEFRESNEL = false;
  42345. _this.FRESNEL = false;
  42346. _this.NORMAL = false;
  42347. _this.UV1 = false;
  42348. _this.UV2 = false;
  42349. _this.VERTEXCOLOR = false;
  42350. _this.VERTEXALPHA = false;
  42351. _this.NUM_BONE_INFLUENCERS = 0;
  42352. _this.BonesPerMesh = 0;
  42353. _this.INSTANCES = false;
  42354. _this.GLOSSINESS = false;
  42355. _this.ROUGHNESS = false;
  42356. _this.EMISSIVEASILLUMINATION = false;
  42357. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42358. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42359. _this.LIGHTMAP = false;
  42360. _this.LIGHTMAPDIRECTUV = 0;
  42361. _this.OBJECTSPACE_NORMALMAP = false;
  42362. _this.USELIGHTMAPASSHADOWMAP = false;
  42363. _this.REFLECTIONMAP_3D = false;
  42364. _this.REFLECTIONMAP_SPHERICAL = false;
  42365. _this.REFLECTIONMAP_PLANAR = false;
  42366. _this.REFLECTIONMAP_CUBIC = false;
  42367. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42368. _this.REFLECTIONMAP_PROJECTION = false;
  42369. _this.REFLECTIONMAP_SKYBOX = false;
  42370. _this.REFLECTIONMAP_EXPLICIT = false;
  42371. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42372. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42373. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42374. _this.INVERTCUBICMAP = false;
  42375. _this.LOGARITHMICDEPTH = false;
  42376. _this.REFRACTION = false;
  42377. _this.REFRACTIONMAP_3D = false;
  42378. _this.REFLECTIONOVERALPHA = false;
  42379. _this.TWOSIDEDLIGHTING = false;
  42380. _this.SHADOWFLOAT = false;
  42381. _this.MORPHTARGETS = false;
  42382. _this.MORPHTARGETS_NORMAL = false;
  42383. _this.MORPHTARGETS_TANGENT = false;
  42384. _this.NUM_MORPH_INFLUENCERS = 0;
  42385. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42386. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42387. _this.IMAGEPROCESSING = false;
  42388. _this.VIGNETTE = false;
  42389. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42390. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42391. _this.TONEMAPPING = false;
  42392. _this.CONTRAST = false;
  42393. _this.COLORCURVES = false;
  42394. _this.COLORGRADING = false;
  42395. _this.COLORGRADING3D = false;
  42396. _this.SAMPLER3DGREENDEPTH = false;
  42397. _this.SAMPLER3DBGRMAP = false;
  42398. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42399. /**
  42400. * If the reflection texture on this material is in linear color space
  42401. * @ignore
  42402. */
  42403. _this.IS_REFLECTION_LINEAR = false;
  42404. /**
  42405. * If the refraction texture on this material is in linear color space
  42406. * @ignore
  42407. */
  42408. _this.IS_REFRACTION_LINEAR = false;
  42409. _this.EXPOSURE = false;
  42410. _this.rebuild();
  42411. return _this;
  42412. }
  42413. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42414. var modes = [
  42415. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42416. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42417. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42418. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42419. ];
  42420. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42421. var mode = modes_1[_i];
  42422. this[mode] = (mode === modeToEnable);
  42423. }
  42424. };
  42425. return StandardMaterialDefines;
  42426. }(BABYLON.MaterialDefines));
  42427. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42428. var StandardMaterial = /** @class */ (function (_super) {
  42429. __extends(StandardMaterial, _super);
  42430. function StandardMaterial(name, scene) {
  42431. var _this = _super.call(this, name, scene) || this;
  42432. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42433. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42434. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42435. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42436. _this.specularPower = 64;
  42437. _this._useAlphaFromDiffuseTexture = false;
  42438. _this._useEmissiveAsIllumination = false;
  42439. _this._linkEmissiveWithDiffuse = false;
  42440. _this._useSpecularOverAlpha = false;
  42441. _this._useReflectionOverAlpha = false;
  42442. _this._disableLighting = false;
  42443. _this._useObjectSpaceNormalMap = false;
  42444. _this._useParallax = false;
  42445. _this._useParallaxOcclusion = false;
  42446. _this.parallaxScaleBias = 0.05;
  42447. _this._roughness = 0;
  42448. _this.indexOfRefraction = 0.98;
  42449. _this.invertRefractionY = true;
  42450. _this._useLightmapAsShadowmap = false;
  42451. _this._useReflectionFresnelFromSpecular = false;
  42452. _this._useGlossinessFromSpecularMapAlpha = false;
  42453. _this._maxSimultaneousLights = 4;
  42454. /**
  42455. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42456. */
  42457. _this._invertNormalMapX = false;
  42458. /**
  42459. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42460. */
  42461. _this._invertNormalMapY = false;
  42462. /**
  42463. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42464. */
  42465. _this._twoSidedLighting = false;
  42466. _this._renderTargets = new BABYLON.SmartArray(16);
  42467. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42468. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42469. // Setup the default processing configuration to the scene.
  42470. _this._attachImageProcessingConfiguration(null);
  42471. _this.getRenderTargetTextures = function () {
  42472. _this._renderTargets.reset();
  42473. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42474. _this._renderTargets.push(_this._reflectionTexture);
  42475. }
  42476. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42477. _this._renderTargets.push(_this._refractionTexture);
  42478. }
  42479. return _this._renderTargets;
  42480. };
  42481. return _this;
  42482. }
  42483. ;
  42484. ;
  42485. ;
  42486. ;
  42487. ;
  42488. ;
  42489. ;
  42490. ;
  42491. ;
  42492. ;
  42493. ;
  42494. ;
  42495. ;
  42496. ;
  42497. ;
  42498. ;
  42499. ;
  42500. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42501. /**
  42502. * Gets the image processing configuration used either in this material.
  42503. */
  42504. get: function () {
  42505. return this._imageProcessingConfiguration;
  42506. },
  42507. /**
  42508. * Sets the Default image processing configuration used either in the this material.
  42509. *
  42510. * If sets to null, the scene one is in use.
  42511. */
  42512. set: function (value) {
  42513. this._attachImageProcessingConfiguration(value);
  42514. // Ensure the effect will be rebuilt.
  42515. this._markAllSubMeshesAsTexturesDirty();
  42516. },
  42517. enumerable: true,
  42518. configurable: true
  42519. });
  42520. /**
  42521. * Attaches a new image processing configuration to the Standard Material.
  42522. * @param configuration
  42523. */
  42524. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42525. var _this = this;
  42526. if (configuration === this._imageProcessingConfiguration) {
  42527. return;
  42528. }
  42529. // Detaches observer.
  42530. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42531. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42532. }
  42533. // Pick the scene configuration if needed.
  42534. if (!configuration) {
  42535. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42536. }
  42537. else {
  42538. this._imageProcessingConfiguration = configuration;
  42539. }
  42540. // Attaches observer.
  42541. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42542. _this._markAllSubMeshesAsImageProcessingDirty();
  42543. });
  42544. };
  42545. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42546. /**
  42547. * Gets wether the color curves effect is enabled.
  42548. */
  42549. get: function () {
  42550. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42551. },
  42552. /**
  42553. * Sets wether the color curves effect is enabled.
  42554. */
  42555. set: function (value) {
  42556. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42557. },
  42558. enumerable: true,
  42559. configurable: true
  42560. });
  42561. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42562. /**
  42563. * Gets wether the color grading effect is enabled.
  42564. */
  42565. get: function () {
  42566. return this.imageProcessingConfiguration.colorGradingEnabled;
  42567. },
  42568. /**
  42569. * Gets wether the color grading effect is enabled.
  42570. */
  42571. set: function (value) {
  42572. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42573. },
  42574. enumerable: true,
  42575. configurable: true
  42576. });
  42577. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42578. /**
  42579. * Gets wether tonemapping is enabled or not.
  42580. */
  42581. get: function () {
  42582. return this._imageProcessingConfiguration.toneMappingEnabled;
  42583. },
  42584. /**
  42585. * Sets wether tonemapping is enabled or not
  42586. */
  42587. set: function (value) {
  42588. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42589. },
  42590. enumerable: true,
  42591. configurable: true
  42592. });
  42593. ;
  42594. ;
  42595. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42596. /**
  42597. * The camera exposure used on this material.
  42598. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42599. * This corresponds to a photographic exposure.
  42600. */
  42601. get: function () {
  42602. return this._imageProcessingConfiguration.exposure;
  42603. },
  42604. /**
  42605. * The camera exposure used on this material.
  42606. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42607. * This corresponds to a photographic exposure.
  42608. */
  42609. set: function (value) {
  42610. this._imageProcessingConfiguration.exposure = value;
  42611. },
  42612. enumerable: true,
  42613. configurable: true
  42614. });
  42615. ;
  42616. ;
  42617. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42618. /**
  42619. * Gets The camera contrast used on this material.
  42620. */
  42621. get: function () {
  42622. return this._imageProcessingConfiguration.contrast;
  42623. },
  42624. /**
  42625. * Sets The camera contrast used on this material.
  42626. */
  42627. set: function (value) {
  42628. this._imageProcessingConfiguration.contrast = value;
  42629. },
  42630. enumerable: true,
  42631. configurable: true
  42632. });
  42633. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42634. /**
  42635. * Gets the Color Grading 2D Lookup Texture.
  42636. */
  42637. get: function () {
  42638. return this._imageProcessingConfiguration.colorGradingTexture;
  42639. },
  42640. /**
  42641. * Sets the Color Grading 2D Lookup Texture.
  42642. */
  42643. set: function (value) {
  42644. this._imageProcessingConfiguration.colorGradingTexture = value;
  42645. },
  42646. enumerable: true,
  42647. configurable: true
  42648. });
  42649. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42650. /**
  42651. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42652. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42653. * 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;
  42654. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42655. */
  42656. get: function () {
  42657. return this._imageProcessingConfiguration.colorCurves;
  42658. },
  42659. /**
  42660. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42661. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42662. * 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;
  42663. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42664. */
  42665. set: function (value) {
  42666. this._imageProcessingConfiguration.colorCurves = value;
  42667. },
  42668. enumerable: true,
  42669. configurable: true
  42670. });
  42671. StandardMaterial.prototype.getClassName = function () {
  42672. return "StandardMaterial";
  42673. };
  42674. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42675. get: function () {
  42676. return this._useLogarithmicDepth;
  42677. },
  42678. set: function (value) {
  42679. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42680. this._markAllSubMeshesAsMiscDirty();
  42681. },
  42682. enumerable: true,
  42683. configurable: true
  42684. });
  42685. StandardMaterial.prototype.needAlphaBlending = function () {
  42686. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42687. };
  42688. StandardMaterial.prototype.needAlphaTesting = function () {
  42689. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42690. };
  42691. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42692. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42693. };
  42694. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42695. return this._diffuseTexture;
  42696. };
  42697. /**
  42698. * Child classes can use it to update shaders
  42699. */
  42700. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42701. if (useInstances === void 0) { useInstances = false; }
  42702. if (subMesh.effect && this.isFrozen) {
  42703. if (this._wasPreviouslyReady && subMesh.effect) {
  42704. return true;
  42705. }
  42706. }
  42707. if (!subMesh._materialDefines) {
  42708. subMesh._materialDefines = new StandardMaterialDefines();
  42709. }
  42710. var scene = this.getScene();
  42711. var defines = subMesh._materialDefines;
  42712. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42713. if (defines._renderId === scene.getRenderId()) {
  42714. return true;
  42715. }
  42716. }
  42717. var engine = scene.getEngine();
  42718. // Lights
  42719. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42720. // Textures
  42721. if (defines._areTexturesDirty) {
  42722. defines._needUVs = false;
  42723. defines.MAINUV1 = false;
  42724. defines.MAINUV2 = false;
  42725. if (scene.texturesEnabled) {
  42726. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42727. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42728. return false;
  42729. }
  42730. else {
  42731. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42732. }
  42733. }
  42734. else {
  42735. defines.DIFFUSE = false;
  42736. }
  42737. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42738. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42739. return false;
  42740. }
  42741. else {
  42742. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42743. }
  42744. }
  42745. else {
  42746. defines.AMBIENT = false;
  42747. }
  42748. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42749. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42750. return false;
  42751. }
  42752. else {
  42753. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42754. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42755. }
  42756. }
  42757. else {
  42758. defines.OPACITY = false;
  42759. }
  42760. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42761. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42762. return false;
  42763. }
  42764. else {
  42765. defines._needNormals = true;
  42766. defines.REFLECTION = true;
  42767. defines.ROUGHNESS = (this._roughness > 0);
  42768. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42769. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42770. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42771. switch (this._reflectionTexture.coordinatesMode) {
  42772. case BABYLON.Texture.CUBIC_MODE:
  42773. case BABYLON.Texture.INVCUBIC_MODE:
  42774. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42775. break;
  42776. case BABYLON.Texture.EXPLICIT_MODE:
  42777. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42778. break;
  42779. case BABYLON.Texture.PLANAR_MODE:
  42780. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42781. break;
  42782. case BABYLON.Texture.PROJECTION_MODE:
  42783. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42784. break;
  42785. case BABYLON.Texture.SKYBOX_MODE:
  42786. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42787. break;
  42788. case BABYLON.Texture.SPHERICAL_MODE:
  42789. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42790. break;
  42791. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42792. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42793. break;
  42794. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42795. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42796. break;
  42797. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42798. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42799. break;
  42800. }
  42801. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42802. }
  42803. }
  42804. else {
  42805. defines.REFLECTION = false;
  42806. }
  42807. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42808. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42809. return false;
  42810. }
  42811. else {
  42812. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42813. }
  42814. }
  42815. else {
  42816. defines.EMISSIVE = false;
  42817. }
  42818. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42819. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42820. return false;
  42821. }
  42822. else {
  42823. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42824. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42825. }
  42826. }
  42827. else {
  42828. defines.LIGHTMAP = false;
  42829. }
  42830. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42831. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42832. return false;
  42833. }
  42834. else {
  42835. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42836. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42837. }
  42838. }
  42839. else {
  42840. defines.SPECULAR = false;
  42841. }
  42842. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42843. // Bump texure can not be not blocking.
  42844. if (!this._bumpTexture.isReady()) {
  42845. return false;
  42846. }
  42847. else {
  42848. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42849. defines.PARALLAX = this._useParallax;
  42850. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42851. }
  42852. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42853. }
  42854. else {
  42855. defines.BUMP = false;
  42856. }
  42857. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42858. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42859. return false;
  42860. }
  42861. else {
  42862. defines._needUVs = true;
  42863. defines.REFRACTION = true;
  42864. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42865. }
  42866. }
  42867. else {
  42868. defines.REFRACTION = false;
  42869. }
  42870. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42871. }
  42872. else {
  42873. defines.DIFFUSE = false;
  42874. defines.AMBIENT = false;
  42875. defines.OPACITY = false;
  42876. defines.REFLECTION = false;
  42877. defines.EMISSIVE = false;
  42878. defines.LIGHTMAP = false;
  42879. defines.BUMP = false;
  42880. defines.REFRACTION = false;
  42881. }
  42882. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42883. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42884. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42885. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42886. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42887. }
  42888. if (defines._areImageProcessingDirty) {
  42889. if (!this._imageProcessingConfiguration.isReady()) {
  42890. return false;
  42891. }
  42892. this._imageProcessingConfiguration.prepareDefines(defines);
  42893. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42894. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42895. }
  42896. if (defines._areFresnelDirty) {
  42897. if (StandardMaterial.FresnelEnabled) {
  42898. // Fresnel
  42899. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42900. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42901. this._reflectionFresnelParameters) {
  42902. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42903. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42904. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42905. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42906. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42907. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42908. defines._needNormals = true;
  42909. defines.FRESNEL = true;
  42910. }
  42911. }
  42912. else {
  42913. defines.FRESNEL = false;
  42914. }
  42915. }
  42916. // Misc.
  42917. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42918. // Attribs
  42919. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42920. // Values that need to be evaluated on every frame
  42921. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42922. // Get correct effect
  42923. if (defines.isDirty) {
  42924. defines.markAsProcessed();
  42925. scene.resetCachedMaterial();
  42926. // Fallbacks
  42927. var fallbacks = new BABYLON.EffectFallbacks();
  42928. if (defines.REFLECTION) {
  42929. fallbacks.addFallback(0, "REFLECTION");
  42930. }
  42931. if (defines.SPECULAR) {
  42932. fallbacks.addFallback(0, "SPECULAR");
  42933. }
  42934. if (defines.BUMP) {
  42935. fallbacks.addFallback(0, "BUMP");
  42936. }
  42937. if (defines.PARALLAX) {
  42938. fallbacks.addFallback(1, "PARALLAX");
  42939. }
  42940. if (defines.PARALLAXOCCLUSION) {
  42941. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42942. }
  42943. if (defines.SPECULAROVERALPHA) {
  42944. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42945. }
  42946. if (defines.FOG) {
  42947. fallbacks.addFallback(1, "FOG");
  42948. }
  42949. if (defines.POINTSIZE) {
  42950. fallbacks.addFallback(0, "POINTSIZE");
  42951. }
  42952. if (defines.LOGARITHMICDEPTH) {
  42953. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42954. }
  42955. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42956. if (defines.SPECULARTERM) {
  42957. fallbacks.addFallback(0, "SPECULARTERM");
  42958. }
  42959. if (defines.DIFFUSEFRESNEL) {
  42960. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42961. }
  42962. if (defines.OPACITYFRESNEL) {
  42963. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42964. }
  42965. if (defines.REFLECTIONFRESNEL) {
  42966. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42967. }
  42968. if (defines.EMISSIVEFRESNEL) {
  42969. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42970. }
  42971. if (defines.FRESNEL) {
  42972. fallbacks.addFallback(4, "FRESNEL");
  42973. }
  42974. //Attributes
  42975. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42976. if (defines.NORMAL) {
  42977. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42978. }
  42979. if (defines.UV1) {
  42980. attribs.push(BABYLON.VertexBuffer.UVKind);
  42981. }
  42982. if (defines.UV2) {
  42983. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42984. }
  42985. if (defines.VERTEXCOLOR) {
  42986. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42987. }
  42988. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42989. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42990. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42991. var shaderName = "default";
  42992. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42993. "vFogInfos", "vFogColor", "pointSize",
  42994. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42995. "mBones",
  42996. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42997. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42998. "vReflectionPosition", "vReflectionSize",
  42999. "logarithmicDepthConstant", "vTangentSpaceParams"
  43000. ];
  43001. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43002. var uniformBuffers = ["Material", "Scene"];
  43003. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43004. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43005. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43006. uniformsNames: uniforms,
  43007. uniformBuffersNames: uniformBuffers,
  43008. samplers: samplers,
  43009. defines: defines,
  43010. maxSimultaneousLights: this._maxSimultaneousLights
  43011. });
  43012. if (this.customShaderNameResolve) {
  43013. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43014. }
  43015. var join = defines.toString();
  43016. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43017. attributes: attribs,
  43018. uniformsNames: uniforms,
  43019. uniformBuffersNames: uniformBuffers,
  43020. samplers: samplers,
  43021. defines: join,
  43022. fallbacks: fallbacks,
  43023. onCompiled: this.onCompiled,
  43024. onError: this.onError,
  43025. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43026. }, engine), defines);
  43027. this.buildUniformLayout();
  43028. }
  43029. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43030. return false;
  43031. }
  43032. defines._renderId = scene.getRenderId();
  43033. this._wasPreviouslyReady = true;
  43034. return true;
  43035. };
  43036. StandardMaterial.prototype.buildUniformLayout = function () {
  43037. // Order is important !
  43038. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43039. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43040. this._uniformBuffer.addUniform("opacityParts", 4);
  43041. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43042. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43043. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43044. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43045. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43046. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43047. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43048. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43049. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43050. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43051. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43052. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43053. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43054. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43055. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43056. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43057. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43058. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43059. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43060. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43061. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43062. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43063. this._uniformBuffer.addUniform("specularMatrix", 16);
  43064. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43065. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43066. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43067. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43068. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43069. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43070. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43071. this._uniformBuffer.addUniform("pointSize", 1);
  43072. this._uniformBuffer.create();
  43073. };
  43074. StandardMaterial.prototype.unbind = function () {
  43075. if (this._activeEffect) {
  43076. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43077. this._activeEffect.setTexture("reflection2DSampler", null);
  43078. }
  43079. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43080. this._activeEffect.setTexture("refraction2DSampler", null);
  43081. }
  43082. }
  43083. _super.prototype.unbind.call(this);
  43084. };
  43085. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43086. var scene = this.getScene();
  43087. var defines = subMesh._materialDefines;
  43088. if (!defines) {
  43089. return;
  43090. }
  43091. var effect = subMesh.effect;
  43092. if (!effect) {
  43093. return;
  43094. }
  43095. this._activeEffect = effect;
  43096. // Matrices
  43097. this.bindOnlyWorldMatrix(world);
  43098. // Normal Matrix
  43099. if (defines.OBJECTSPACE_NORMALMAP) {
  43100. world.toNormalMatrix(this._normalMatrix);
  43101. this.bindOnlyNormalMatrix(this._normalMatrix);
  43102. }
  43103. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43104. // Bones
  43105. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43106. if (mustRebind) {
  43107. this._uniformBuffer.bindToEffect(effect, "Material");
  43108. this.bindViewProjection(effect);
  43109. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43110. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43111. // Fresnel
  43112. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43113. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43114. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43115. }
  43116. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43117. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43118. }
  43119. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43120. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43121. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43122. }
  43123. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43124. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43125. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43126. }
  43127. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43128. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43129. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43130. }
  43131. }
  43132. // Textures
  43133. if (scene.texturesEnabled) {
  43134. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43135. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43136. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43137. }
  43138. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43139. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43140. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43141. }
  43142. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43143. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43144. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43145. }
  43146. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43147. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43148. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43149. if (this._reflectionTexture.boundingBoxSize) {
  43150. var cubeTexture = this._reflectionTexture;
  43151. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43152. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43153. }
  43154. }
  43155. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43156. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43157. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43158. }
  43159. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43160. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43161. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43162. }
  43163. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43164. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43165. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43166. }
  43167. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43168. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43169. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43170. if (scene._mirroredCameraPosition) {
  43171. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43172. }
  43173. else {
  43174. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43175. }
  43176. }
  43177. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43178. var depth = 1.0;
  43179. if (!this._refractionTexture.isCube) {
  43180. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43181. if (this._refractionTexture.depth) {
  43182. depth = this._refractionTexture.depth;
  43183. }
  43184. }
  43185. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43186. }
  43187. }
  43188. // Point size
  43189. if (this.pointsCloud) {
  43190. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43191. }
  43192. if (defines.SPECULARTERM) {
  43193. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43194. }
  43195. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43196. // Diffuse
  43197. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43198. }
  43199. // Textures
  43200. if (scene.texturesEnabled) {
  43201. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43202. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43203. }
  43204. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43205. effect.setTexture("ambientSampler", this._ambientTexture);
  43206. }
  43207. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43208. effect.setTexture("opacitySampler", this._opacityTexture);
  43209. }
  43210. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43211. if (this._reflectionTexture.isCube) {
  43212. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43213. }
  43214. else {
  43215. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43216. }
  43217. }
  43218. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43219. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43220. }
  43221. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43222. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43223. }
  43224. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43225. effect.setTexture("specularSampler", this._specularTexture);
  43226. }
  43227. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43228. effect.setTexture("bumpSampler", this._bumpTexture);
  43229. }
  43230. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43231. var depth = 1.0;
  43232. if (this._refractionTexture.isCube) {
  43233. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43234. }
  43235. else {
  43236. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43237. }
  43238. }
  43239. }
  43240. // Clip plane
  43241. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43242. // Colors
  43243. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43244. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43245. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43246. }
  43247. if (mustRebind || !this.isFrozen) {
  43248. // Lights
  43249. if (scene.lightsEnabled && !this._disableLighting) {
  43250. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43251. }
  43252. // View
  43253. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43254. this.bindView(effect);
  43255. }
  43256. // Fog
  43257. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43258. // Morph targets
  43259. if (defines.NUM_MORPH_INFLUENCERS) {
  43260. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43261. }
  43262. // Log. depth
  43263. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43264. // image processing
  43265. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43266. this._imageProcessingConfiguration.bind(this._activeEffect);
  43267. }
  43268. }
  43269. this._uniformBuffer.update();
  43270. this._afterBind(mesh, this._activeEffect);
  43271. };
  43272. StandardMaterial.prototype.getAnimatables = function () {
  43273. var results = [];
  43274. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43275. results.push(this._diffuseTexture);
  43276. }
  43277. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43278. results.push(this._ambientTexture);
  43279. }
  43280. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43281. results.push(this._opacityTexture);
  43282. }
  43283. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43284. results.push(this._reflectionTexture);
  43285. }
  43286. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43287. results.push(this._emissiveTexture);
  43288. }
  43289. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43290. results.push(this._specularTexture);
  43291. }
  43292. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43293. results.push(this._bumpTexture);
  43294. }
  43295. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43296. results.push(this._lightmapTexture);
  43297. }
  43298. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43299. results.push(this._refractionTexture);
  43300. }
  43301. return results;
  43302. };
  43303. StandardMaterial.prototype.getActiveTextures = function () {
  43304. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43305. if (this._diffuseTexture) {
  43306. activeTextures.push(this._diffuseTexture);
  43307. }
  43308. if (this._ambientTexture) {
  43309. activeTextures.push(this._ambientTexture);
  43310. }
  43311. if (this._opacityTexture) {
  43312. activeTextures.push(this._opacityTexture);
  43313. }
  43314. if (this._reflectionTexture) {
  43315. activeTextures.push(this._reflectionTexture);
  43316. }
  43317. if (this._emissiveTexture) {
  43318. activeTextures.push(this._emissiveTexture);
  43319. }
  43320. if (this._specularTexture) {
  43321. activeTextures.push(this._specularTexture);
  43322. }
  43323. if (this._bumpTexture) {
  43324. activeTextures.push(this._bumpTexture);
  43325. }
  43326. if (this._lightmapTexture) {
  43327. activeTextures.push(this._lightmapTexture);
  43328. }
  43329. if (this._refractionTexture) {
  43330. activeTextures.push(this._refractionTexture);
  43331. }
  43332. return activeTextures;
  43333. };
  43334. StandardMaterial.prototype.hasTexture = function (texture) {
  43335. if (_super.prototype.hasTexture.call(this, texture)) {
  43336. return true;
  43337. }
  43338. if (this._diffuseTexture === texture) {
  43339. return true;
  43340. }
  43341. if (this._ambientTexture === texture) {
  43342. return true;
  43343. }
  43344. if (this._opacityTexture === texture) {
  43345. return true;
  43346. }
  43347. if (this._reflectionTexture === texture) {
  43348. return true;
  43349. }
  43350. if (this._emissiveTexture === texture) {
  43351. return true;
  43352. }
  43353. if (this._specularTexture === texture) {
  43354. return true;
  43355. }
  43356. if (this._bumpTexture === texture) {
  43357. return true;
  43358. }
  43359. if (this._lightmapTexture === texture) {
  43360. return true;
  43361. }
  43362. if (this._refractionTexture === texture) {
  43363. return true;
  43364. }
  43365. return false;
  43366. };
  43367. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43368. if (forceDisposeTextures) {
  43369. if (this._diffuseTexture) {
  43370. this._diffuseTexture.dispose();
  43371. }
  43372. if (this._ambientTexture) {
  43373. this._ambientTexture.dispose();
  43374. }
  43375. if (this._opacityTexture) {
  43376. this._opacityTexture.dispose();
  43377. }
  43378. if (this._reflectionTexture) {
  43379. this._reflectionTexture.dispose();
  43380. }
  43381. if (this._emissiveTexture) {
  43382. this._emissiveTexture.dispose();
  43383. }
  43384. if (this._specularTexture) {
  43385. this._specularTexture.dispose();
  43386. }
  43387. if (this._bumpTexture) {
  43388. this._bumpTexture.dispose();
  43389. }
  43390. if (this._lightmapTexture) {
  43391. this._lightmapTexture.dispose();
  43392. }
  43393. if (this._refractionTexture) {
  43394. this._refractionTexture.dispose();
  43395. }
  43396. }
  43397. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43398. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43399. }
  43400. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43401. };
  43402. StandardMaterial.prototype.clone = function (name) {
  43403. var _this = this;
  43404. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43405. result.name = name;
  43406. result.id = name;
  43407. return result;
  43408. };
  43409. StandardMaterial.prototype.serialize = function () {
  43410. return BABYLON.SerializationHelper.Serialize(this);
  43411. };
  43412. // Statics
  43413. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43414. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43415. };
  43416. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43417. get: function () {
  43418. return StandardMaterial._DiffuseTextureEnabled;
  43419. },
  43420. set: function (value) {
  43421. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43422. return;
  43423. }
  43424. StandardMaterial._DiffuseTextureEnabled = value;
  43425. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43426. },
  43427. enumerable: true,
  43428. configurable: true
  43429. });
  43430. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43431. get: function () {
  43432. return StandardMaterial._AmbientTextureEnabled;
  43433. },
  43434. set: function (value) {
  43435. if (StandardMaterial._AmbientTextureEnabled === value) {
  43436. return;
  43437. }
  43438. StandardMaterial._AmbientTextureEnabled = value;
  43439. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43440. },
  43441. enumerable: true,
  43442. configurable: true
  43443. });
  43444. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43445. get: function () {
  43446. return StandardMaterial._OpacityTextureEnabled;
  43447. },
  43448. set: function (value) {
  43449. if (StandardMaterial._OpacityTextureEnabled === value) {
  43450. return;
  43451. }
  43452. StandardMaterial._OpacityTextureEnabled = value;
  43453. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43454. },
  43455. enumerable: true,
  43456. configurable: true
  43457. });
  43458. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43459. get: function () {
  43460. return StandardMaterial._ReflectionTextureEnabled;
  43461. },
  43462. set: function (value) {
  43463. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43464. return;
  43465. }
  43466. StandardMaterial._ReflectionTextureEnabled = value;
  43467. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43468. },
  43469. enumerable: true,
  43470. configurable: true
  43471. });
  43472. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43473. get: function () {
  43474. return StandardMaterial._EmissiveTextureEnabled;
  43475. },
  43476. set: function (value) {
  43477. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43478. return;
  43479. }
  43480. StandardMaterial._EmissiveTextureEnabled = value;
  43481. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43482. },
  43483. enumerable: true,
  43484. configurable: true
  43485. });
  43486. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43487. get: function () {
  43488. return StandardMaterial._SpecularTextureEnabled;
  43489. },
  43490. set: function (value) {
  43491. if (StandardMaterial._SpecularTextureEnabled === value) {
  43492. return;
  43493. }
  43494. StandardMaterial._SpecularTextureEnabled = value;
  43495. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43501. get: function () {
  43502. return StandardMaterial._BumpTextureEnabled;
  43503. },
  43504. set: function (value) {
  43505. if (StandardMaterial._BumpTextureEnabled === value) {
  43506. return;
  43507. }
  43508. StandardMaterial._BumpTextureEnabled = value;
  43509. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43510. },
  43511. enumerable: true,
  43512. configurable: true
  43513. });
  43514. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43515. get: function () {
  43516. return StandardMaterial._LightmapTextureEnabled;
  43517. },
  43518. set: function (value) {
  43519. if (StandardMaterial._LightmapTextureEnabled === value) {
  43520. return;
  43521. }
  43522. StandardMaterial._LightmapTextureEnabled = value;
  43523. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43524. },
  43525. enumerable: true,
  43526. configurable: true
  43527. });
  43528. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43529. get: function () {
  43530. return StandardMaterial._RefractionTextureEnabled;
  43531. },
  43532. set: function (value) {
  43533. if (StandardMaterial._RefractionTextureEnabled === value) {
  43534. return;
  43535. }
  43536. StandardMaterial._RefractionTextureEnabled = value;
  43537. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43538. },
  43539. enumerable: true,
  43540. configurable: true
  43541. });
  43542. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43543. get: function () {
  43544. return StandardMaterial._ColorGradingTextureEnabled;
  43545. },
  43546. set: function (value) {
  43547. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43548. return;
  43549. }
  43550. StandardMaterial._ColorGradingTextureEnabled = value;
  43551. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43552. },
  43553. enumerable: true,
  43554. configurable: true
  43555. });
  43556. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43557. get: function () {
  43558. return StandardMaterial._FresnelEnabled;
  43559. },
  43560. set: function (value) {
  43561. if (StandardMaterial._FresnelEnabled === value) {
  43562. return;
  43563. }
  43564. StandardMaterial._FresnelEnabled = value;
  43565. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43566. },
  43567. enumerable: true,
  43568. configurable: true
  43569. });
  43570. // Flags used to enable or disable a type of texture for all Standard Materials
  43571. StandardMaterial._DiffuseTextureEnabled = true;
  43572. StandardMaterial._AmbientTextureEnabled = true;
  43573. StandardMaterial._OpacityTextureEnabled = true;
  43574. StandardMaterial._ReflectionTextureEnabled = true;
  43575. StandardMaterial._EmissiveTextureEnabled = true;
  43576. StandardMaterial._SpecularTextureEnabled = true;
  43577. StandardMaterial._BumpTextureEnabled = true;
  43578. StandardMaterial._LightmapTextureEnabled = true;
  43579. StandardMaterial._RefractionTextureEnabled = true;
  43580. StandardMaterial._ColorGradingTextureEnabled = true;
  43581. StandardMaterial._FresnelEnabled = true;
  43582. __decorate([
  43583. BABYLON.serializeAsTexture("diffuseTexture")
  43584. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43585. __decorate([
  43586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43587. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43588. __decorate([
  43589. BABYLON.serializeAsTexture("ambientTexture")
  43590. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43591. __decorate([
  43592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43593. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43594. __decorate([
  43595. BABYLON.serializeAsTexture("opacityTexture")
  43596. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43597. __decorate([
  43598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43599. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43600. __decorate([
  43601. BABYLON.serializeAsTexture("reflectionTexture")
  43602. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43603. __decorate([
  43604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43605. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43606. __decorate([
  43607. BABYLON.serializeAsTexture("emissiveTexture")
  43608. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43609. __decorate([
  43610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43611. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43612. __decorate([
  43613. BABYLON.serializeAsTexture("specularTexture")
  43614. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43615. __decorate([
  43616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43617. ], StandardMaterial.prototype, "specularTexture", void 0);
  43618. __decorate([
  43619. BABYLON.serializeAsTexture("bumpTexture")
  43620. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43621. __decorate([
  43622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43623. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43624. __decorate([
  43625. BABYLON.serializeAsTexture("lightmapTexture")
  43626. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43627. __decorate([
  43628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43629. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43630. __decorate([
  43631. BABYLON.serializeAsTexture("refractionTexture")
  43632. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43633. __decorate([
  43634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43635. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43636. __decorate([
  43637. BABYLON.serializeAsColor3("ambient")
  43638. ], StandardMaterial.prototype, "ambientColor", void 0);
  43639. __decorate([
  43640. BABYLON.serializeAsColor3("diffuse")
  43641. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43642. __decorate([
  43643. BABYLON.serializeAsColor3("specular")
  43644. ], StandardMaterial.prototype, "specularColor", void 0);
  43645. __decorate([
  43646. BABYLON.serializeAsColor3("emissive")
  43647. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43648. __decorate([
  43649. BABYLON.serialize()
  43650. ], StandardMaterial.prototype, "specularPower", void 0);
  43651. __decorate([
  43652. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43653. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43654. __decorate([
  43655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43656. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43657. __decorate([
  43658. BABYLON.serialize("useEmissiveAsIllumination")
  43659. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43660. __decorate([
  43661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43662. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43663. __decorate([
  43664. BABYLON.serialize("linkEmissiveWithDiffuse")
  43665. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43666. __decorate([
  43667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43668. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43669. __decorate([
  43670. BABYLON.serialize("useSpecularOverAlpha")
  43671. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43672. __decorate([
  43673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43674. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43675. __decorate([
  43676. BABYLON.serialize("useReflectionOverAlpha")
  43677. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43678. __decorate([
  43679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43680. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43681. __decorate([
  43682. BABYLON.serialize("disableLighting")
  43683. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43684. __decorate([
  43685. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43686. ], StandardMaterial.prototype, "disableLighting", void 0);
  43687. __decorate([
  43688. BABYLON.serialize("useObjectSpaceNormalMap")
  43689. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43690. __decorate([
  43691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43692. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43693. __decorate([
  43694. BABYLON.serialize("useParallax")
  43695. ], StandardMaterial.prototype, "_useParallax", void 0);
  43696. __decorate([
  43697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43698. ], StandardMaterial.prototype, "useParallax", void 0);
  43699. __decorate([
  43700. BABYLON.serialize("useParallaxOcclusion")
  43701. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43702. __decorate([
  43703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43704. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43705. __decorate([
  43706. BABYLON.serialize()
  43707. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43708. __decorate([
  43709. BABYLON.serialize("roughness")
  43710. ], StandardMaterial.prototype, "_roughness", void 0);
  43711. __decorate([
  43712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43713. ], StandardMaterial.prototype, "roughness", void 0);
  43714. __decorate([
  43715. BABYLON.serialize()
  43716. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43717. __decorate([
  43718. BABYLON.serialize()
  43719. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43720. __decorate([
  43721. BABYLON.serialize("useLightmapAsShadowmap")
  43722. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43723. __decorate([
  43724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43725. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43726. __decorate([
  43727. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43728. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43729. __decorate([
  43730. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43731. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43732. __decorate([
  43733. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43734. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43735. __decorate([
  43736. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43737. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43738. __decorate([
  43739. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43740. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43741. __decorate([
  43742. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43743. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43744. __decorate([
  43745. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43746. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43747. __decorate([
  43748. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43749. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43750. __decorate([
  43751. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43752. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43753. __decorate([
  43754. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43755. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43756. __decorate([
  43757. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43758. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43759. __decorate([
  43760. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43761. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43762. __decorate([
  43763. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43764. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43765. __decorate([
  43766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43767. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43768. __decorate([
  43769. BABYLON.serialize("maxSimultaneousLights")
  43770. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43771. __decorate([
  43772. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43773. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43774. __decorate([
  43775. BABYLON.serialize("invertNormalMapX")
  43776. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43777. __decorate([
  43778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43779. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43780. __decorate([
  43781. BABYLON.serialize("invertNormalMapY")
  43782. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43783. __decorate([
  43784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43785. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43786. __decorate([
  43787. BABYLON.serialize("twoSidedLighting")
  43788. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43789. __decorate([
  43790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43791. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43792. __decorate([
  43793. BABYLON.serialize()
  43794. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43795. return StandardMaterial;
  43796. }(BABYLON.PushMaterial));
  43797. BABYLON.StandardMaterial = StandardMaterial;
  43798. })(BABYLON || (BABYLON = {}));
  43799. //# sourceMappingURL=babylon.standardMaterial.js.map
  43800. "use strict";
  43801. var BABYLON;
  43802. (function (BABYLON) {
  43803. /**
  43804. * Manages the defines for the PBR Material.
  43805. * @ignoreChildren
  43806. */
  43807. var PBRMaterialDefines = /** @class */ (function (_super) {
  43808. __extends(PBRMaterialDefines, _super);
  43809. /**
  43810. * Initializes the PBR Material defines.
  43811. */
  43812. function PBRMaterialDefines() {
  43813. var _this = _super.call(this) || this;
  43814. _this.PBR = true;
  43815. _this.MAINUV1 = false;
  43816. _this.MAINUV2 = false;
  43817. _this.UV1 = false;
  43818. _this.UV2 = false;
  43819. _this.ALBEDO = false;
  43820. _this.ALBEDODIRECTUV = 0;
  43821. _this.VERTEXCOLOR = false;
  43822. _this.AMBIENT = false;
  43823. _this.AMBIENTDIRECTUV = 0;
  43824. _this.AMBIENTINGRAYSCALE = false;
  43825. _this.OPACITY = false;
  43826. _this.VERTEXALPHA = false;
  43827. _this.OPACITYDIRECTUV = 0;
  43828. _this.OPACITYRGB = false;
  43829. _this.ALPHATEST = false;
  43830. _this.DEPTHPREPASS = false;
  43831. _this.ALPHABLEND = false;
  43832. _this.ALPHAFROMALBEDO = false;
  43833. _this.ALPHATESTVALUE = "0.5";
  43834. _this.SPECULAROVERALPHA = false;
  43835. _this.RADIANCEOVERALPHA = false;
  43836. _this.ALPHAFRESNEL = false;
  43837. _this.LINEARALPHAFRESNEL = false;
  43838. _this.PREMULTIPLYALPHA = false;
  43839. _this.EMISSIVE = false;
  43840. _this.EMISSIVEDIRECTUV = 0;
  43841. _this.REFLECTIVITY = false;
  43842. _this.REFLECTIVITYDIRECTUV = 0;
  43843. _this.SPECULARTERM = false;
  43844. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43845. _this.MICROSURFACEAUTOMATIC = false;
  43846. _this.LODBASEDMICROSFURACE = false;
  43847. _this.MICROSURFACEMAP = false;
  43848. _this.MICROSURFACEMAPDIRECTUV = 0;
  43849. _this.METALLICWORKFLOW = false;
  43850. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43851. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43852. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43853. _this.AOSTOREINMETALMAPRED = false;
  43854. _this.ENVIRONMENTBRDF = false;
  43855. _this.NORMAL = false;
  43856. _this.TANGENT = false;
  43857. _this.BUMP = false;
  43858. _this.BUMPDIRECTUV = 0;
  43859. _this.OBJECTSPACE_NORMALMAP = false;
  43860. _this.PARALLAX = false;
  43861. _this.PARALLAXOCCLUSION = false;
  43862. _this.NORMALXYSCALE = true;
  43863. _this.LIGHTMAP = false;
  43864. _this.LIGHTMAPDIRECTUV = 0;
  43865. _this.USELIGHTMAPASSHADOWMAP = false;
  43866. _this.GAMMALIGHTMAP = false;
  43867. _this.REFLECTION = false;
  43868. _this.REFLECTIONMAP_3D = false;
  43869. _this.REFLECTIONMAP_SPHERICAL = false;
  43870. _this.REFLECTIONMAP_PLANAR = false;
  43871. _this.REFLECTIONMAP_CUBIC = false;
  43872. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43873. _this.REFLECTIONMAP_PROJECTION = false;
  43874. _this.REFLECTIONMAP_SKYBOX = false;
  43875. _this.REFLECTIONMAP_EXPLICIT = false;
  43876. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43877. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43878. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43879. _this.INVERTCUBICMAP = false;
  43880. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43881. _this.USESPHERICALINVERTEX = false;
  43882. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43883. _this.LODINREFLECTIONALPHA = false;
  43884. _this.GAMMAREFLECTION = false;
  43885. _this.RADIANCEOCCLUSION = false;
  43886. _this.HORIZONOCCLUSION = false;
  43887. _this.REFRACTION = false;
  43888. _this.REFRACTIONMAP_3D = false;
  43889. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43890. _this.LODINREFRACTIONALPHA = false;
  43891. _this.GAMMAREFRACTION = false;
  43892. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43893. _this.INSTANCES = false;
  43894. _this.NUM_BONE_INFLUENCERS = 0;
  43895. _this.BonesPerMesh = 0;
  43896. _this.NONUNIFORMSCALING = false;
  43897. _this.MORPHTARGETS = false;
  43898. _this.MORPHTARGETS_NORMAL = false;
  43899. _this.MORPHTARGETS_TANGENT = false;
  43900. _this.NUM_MORPH_INFLUENCERS = 0;
  43901. _this.IMAGEPROCESSING = false;
  43902. _this.VIGNETTE = false;
  43903. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43904. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43905. _this.TONEMAPPING = false;
  43906. _this.CONTRAST = false;
  43907. _this.COLORCURVES = false;
  43908. _this.COLORGRADING = false;
  43909. _this.COLORGRADING3D = false;
  43910. _this.SAMPLER3DGREENDEPTH = false;
  43911. _this.SAMPLER3DBGRMAP = false;
  43912. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43913. _this.EXPOSURE = false;
  43914. _this.USEPHYSICALLIGHTFALLOFF = false;
  43915. _this.TWOSIDEDLIGHTING = false;
  43916. _this.SHADOWFLOAT = false;
  43917. _this.CLIPPLANE = false;
  43918. _this.POINTSIZE = false;
  43919. _this.FOG = false;
  43920. _this.LOGARITHMICDEPTH = false;
  43921. _this.FORCENORMALFORWARD = false;
  43922. _this.GEOMETRYAA = false;
  43923. _this.UNLIT = false;
  43924. _this.rebuild();
  43925. return _this;
  43926. }
  43927. /**
  43928. * Resets the PBR Material defines.
  43929. */
  43930. PBRMaterialDefines.prototype.reset = function () {
  43931. _super.prototype.reset.call(this);
  43932. this.ALPHATESTVALUE = "0.5";
  43933. this.PBR = true;
  43934. };
  43935. return PBRMaterialDefines;
  43936. }(BABYLON.MaterialDefines));
  43937. /**
  43938. * The Physically based material base class of BJS.
  43939. *
  43940. * This offers the main features of a standard PBR material.
  43941. * For more information, please refer to the documentation :
  43942. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43943. */
  43944. var PBRBaseMaterial = /** @class */ (function (_super) {
  43945. __extends(PBRBaseMaterial, _super);
  43946. /**
  43947. * Instantiates a new PBRMaterial instance.
  43948. *
  43949. * @param name The material name
  43950. * @param scene The scene the material will be use in.
  43951. */
  43952. function PBRBaseMaterial(name, scene) {
  43953. var _this = _super.call(this, name, scene) || this;
  43954. /**
  43955. * Intensity of the direct lights e.g. the four lights available in your scene.
  43956. * This impacts both the direct diffuse and specular highlights.
  43957. */
  43958. _this._directIntensity = 1.0;
  43959. /**
  43960. * Intensity of the emissive part of the material.
  43961. * This helps controlling the emissive effect without modifying the emissive color.
  43962. */
  43963. _this._emissiveIntensity = 1.0;
  43964. /**
  43965. * Intensity of the environment e.g. how much the environment will light the object
  43966. * either through harmonics for rough material or through the refelction for shiny ones.
  43967. */
  43968. _this._environmentIntensity = 1.0;
  43969. /**
  43970. * This is a special control allowing the reduction of the specular highlights coming from the
  43971. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43972. */
  43973. _this._specularIntensity = 1.0;
  43974. /**
  43975. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43976. */
  43977. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43978. /**
  43979. * Debug Control allowing disabling the bump map on this material.
  43980. */
  43981. _this._disableBumpMap = false;
  43982. /**
  43983. * AKA Occlusion Texture Intensity in other nomenclature.
  43984. */
  43985. _this._ambientTextureStrength = 1.0;
  43986. /**
  43987. * The color of a material in ambient lighting.
  43988. */
  43989. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43990. /**
  43991. * AKA Diffuse Color in other nomenclature.
  43992. */
  43993. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43994. /**
  43995. * AKA Specular Color in other nomenclature.
  43996. */
  43997. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43998. /**
  43999. * The color applied when light is reflected from a material.
  44000. */
  44001. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44002. /**
  44003. * The color applied when light is emitted from a material.
  44004. */
  44005. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44006. /**
  44007. * AKA Glossiness in other nomenclature.
  44008. */
  44009. _this._microSurface = 0.9;
  44010. /**
  44011. * source material index of refraction (IOR)' / 'destination material IOR.
  44012. */
  44013. _this._indexOfRefraction = 0.66;
  44014. /**
  44015. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44016. */
  44017. _this._invertRefractionY = false;
  44018. /**
  44019. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44020. * Materials half opaque for instance using refraction could benefit from this control.
  44021. */
  44022. _this._linkRefractionWithTransparency = false;
  44023. /**
  44024. * Specifies that the material will use the light map as a show map.
  44025. */
  44026. _this._useLightmapAsShadowmap = false;
  44027. /**
  44028. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44029. * makes the reflect vector face the model (under horizon).
  44030. */
  44031. _this._useHorizonOcclusion = true;
  44032. /**
  44033. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44034. * too much the area relying on ambient texture to define their ambient occlusion.
  44035. */
  44036. _this._useRadianceOcclusion = true;
  44037. /**
  44038. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44039. */
  44040. _this._useAlphaFromAlbedoTexture = false;
  44041. /**
  44042. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44043. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44044. */
  44045. _this._useSpecularOverAlpha = true;
  44046. /**
  44047. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44048. */
  44049. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44050. /**
  44051. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44052. */
  44053. _this._useRoughnessFromMetallicTextureAlpha = true;
  44054. /**
  44055. * Specifies if the metallic texture contains the roughness information in its green channel.
  44056. */
  44057. _this._useRoughnessFromMetallicTextureGreen = false;
  44058. /**
  44059. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44060. */
  44061. _this._useMetallnessFromMetallicTextureBlue = false;
  44062. /**
  44063. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44064. */
  44065. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44066. /**
  44067. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44068. */
  44069. _this._useAmbientInGrayScale = false;
  44070. /**
  44071. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44072. * The material will try to infer what glossiness each pixel should be.
  44073. */
  44074. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44075. /**
  44076. * BJS is using an harcoded light falloff based on a manually sets up range.
  44077. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44078. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44079. */
  44080. _this._usePhysicalLightFalloff = true;
  44081. /**
  44082. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44083. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44084. */
  44085. _this._useRadianceOverAlpha = true;
  44086. /**
  44087. * Allows using an object space normal map (instead of tangent space).
  44088. */
  44089. _this._useObjectSpaceNormalMap = false;
  44090. /**
  44091. * Allows using the bump map in parallax mode.
  44092. */
  44093. _this._useParallax = false;
  44094. /**
  44095. * Allows using the bump map in parallax occlusion mode.
  44096. */
  44097. _this._useParallaxOcclusion = false;
  44098. /**
  44099. * Controls the scale bias of the parallax mode.
  44100. */
  44101. _this._parallaxScaleBias = 0.05;
  44102. /**
  44103. * If sets to true, disables all the lights affecting the material.
  44104. */
  44105. _this._disableLighting = false;
  44106. /**
  44107. * Number of Simultaneous lights allowed on the material.
  44108. */
  44109. _this._maxSimultaneousLights = 4;
  44110. /**
  44111. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44112. */
  44113. _this._invertNormalMapX = false;
  44114. /**
  44115. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44116. */
  44117. _this._invertNormalMapY = false;
  44118. /**
  44119. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44120. */
  44121. _this._twoSidedLighting = false;
  44122. /**
  44123. * Defines the alpha limits in alpha test mode.
  44124. */
  44125. _this._alphaCutOff = 0.4;
  44126. /**
  44127. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44128. */
  44129. _this._forceAlphaTest = false;
  44130. /**
  44131. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44132. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44133. */
  44134. _this._useAlphaFresnel = false;
  44135. /**
  44136. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44137. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44138. */
  44139. _this._useLinearAlphaFresnel = false;
  44140. /**
  44141. * The transparency mode of the material.
  44142. */
  44143. _this._transparencyMode = null;
  44144. /**
  44145. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44146. * from cos thetav and roughness:
  44147. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44148. */
  44149. _this._environmentBRDFTexture = null;
  44150. /**
  44151. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44152. */
  44153. _this._forceIrradianceInFragment = false;
  44154. /**
  44155. * Force normal to face away from face.
  44156. */
  44157. _this._forceNormalForward = false;
  44158. /**
  44159. * Enables specular anti aliasing in the PBR shader.
  44160. * It will both interacts on the Geometry for analytical and IBL lighting.
  44161. * It also prefilter the roughness map based on the bump values.
  44162. */
  44163. _this._enableSpecularAntiAliasing = false;
  44164. /**
  44165. * Stores the available render targets.
  44166. */
  44167. _this._renderTargets = new BABYLON.SmartArray(16);
  44168. /**
  44169. * Sets the global ambient color for the material used in lighting calculations.
  44170. */
  44171. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44172. /**
  44173. * If set to true, no lighting calculations will be applied.
  44174. */
  44175. _this._unlit = false;
  44176. // Setup the default processing configuration to the scene.
  44177. _this._attachImageProcessingConfiguration(null);
  44178. _this.getRenderTargetTextures = function () {
  44179. _this._renderTargets.reset();
  44180. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44181. _this._renderTargets.push(_this._reflectionTexture);
  44182. }
  44183. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44184. _this._renderTargets.push(_this._refractionTexture);
  44185. }
  44186. return _this._renderTargets;
  44187. };
  44188. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44189. return _this;
  44190. }
  44191. /**
  44192. * Attaches a new image processing configuration to the PBR Material.
  44193. * @param configuration
  44194. */
  44195. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44196. var _this = this;
  44197. if (configuration === this._imageProcessingConfiguration) {
  44198. return;
  44199. }
  44200. // Detaches observer.
  44201. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44202. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44203. }
  44204. // Pick the scene configuration if needed.
  44205. if (!configuration) {
  44206. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44207. }
  44208. else {
  44209. this._imageProcessingConfiguration = configuration;
  44210. }
  44211. // Attaches observer.
  44212. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44213. _this._markAllSubMeshesAsImageProcessingDirty();
  44214. });
  44215. };
  44216. /**
  44217. * Gets the name of the material class.
  44218. */
  44219. PBRBaseMaterial.prototype.getClassName = function () {
  44220. return "PBRBaseMaterial";
  44221. };
  44222. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44223. /**
  44224. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44225. */
  44226. get: function () {
  44227. return this._useLogarithmicDepth;
  44228. },
  44229. /**
  44230. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44231. */
  44232. set: function (value) {
  44233. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44234. },
  44235. enumerable: true,
  44236. configurable: true
  44237. });
  44238. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44239. /**
  44240. * Gets the current transparency mode.
  44241. */
  44242. get: function () {
  44243. return this._transparencyMode;
  44244. },
  44245. /**
  44246. * Sets the transparency mode of the material.
  44247. */
  44248. set: function (value) {
  44249. if (this._transparencyMode === value) {
  44250. return;
  44251. }
  44252. this._transparencyMode = value;
  44253. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44254. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44255. },
  44256. enumerable: true,
  44257. configurable: true
  44258. });
  44259. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44260. /**
  44261. * Returns true if alpha blending should be disabled.
  44262. */
  44263. get: function () {
  44264. return (this._linkRefractionWithTransparency ||
  44265. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44266. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44267. },
  44268. enumerable: true,
  44269. configurable: true
  44270. });
  44271. /**
  44272. * Specifies whether or not this material should be rendered in alpha blend mode.
  44273. */
  44274. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44275. if (this._disableAlphaBlending) {
  44276. return false;
  44277. }
  44278. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44279. };
  44280. /**
  44281. * Specifies if the mesh will require alpha blending.
  44282. * @param mesh - BJS mesh.
  44283. */
  44284. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44285. if (this._disableAlphaBlending) {
  44286. return false;
  44287. }
  44288. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44289. };
  44290. /**
  44291. * Specifies whether or not this material should be rendered in alpha test mode.
  44292. */
  44293. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44294. if (this._forceAlphaTest) {
  44295. return true;
  44296. }
  44297. if (this._linkRefractionWithTransparency) {
  44298. return false;
  44299. }
  44300. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44301. };
  44302. /**
  44303. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44304. */
  44305. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44306. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44307. };
  44308. /**
  44309. * Gets the texture used for the alpha test.
  44310. */
  44311. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44312. return this._albedoTexture;
  44313. };
  44314. /**
  44315. * Specifies that the submesh is ready to be used.
  44316. * @param mesh - BJS mesh.
  44317. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44318. * @param useInstances - Specifies that instances should be used.
  44319. * @returns - boolean indicating that the submesh is ready or not.
  44320. */
  44321. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44322. if (subMesh.effect && this.isFrozen) {
  44323. if (this._wasPreviouslyReady) {
  44324. return true;
  44325. }
  44326. }
  44327. if (!subMesh._materialDefines) {
  44328. subMesh._materialDefines = new PBRMaterialDefines();
  44329. }
  44330. var defines = subMesh._materialDefines;
  44331. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44332. if (defines._renderId === this.getScene().getRenderId()) {
  44333. return true;
  44334. }
  44335. }
  44336. var scene = this.getScene();
  44337. var engine = scene.getEngine();
  44338. if (defines._areTexturesDirty) {
  44339. if (scene.texturesEnabled) {
  44340. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44341. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44342. return false;
  44343. }
  44344. }
  44345. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44346. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44347. return false;
  44348. }
  44349. }
  44350. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44351. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44352. return false;
  44353. }
  44354. }
  44355. var reflectionTexture = this._getReflectionTexture();
  44356. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44357. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44358. return false;
  44359. }
  44360. }
  44361. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44362. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44363. return false;
  44364. }
  44365. }
  44366. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44367. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44368. return false;
  44369. }
  44370. }
  44371. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44372. if (this._metallicTexture) {
  44373. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44374. return false;
  44375. }
  44376. }
  44377. else if (this._reflectivityTexture) {
  44378. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44379. return false;
  44380. }
  44381. }
  44382. if (this._microSurfaceTexture) {
  44383. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44384. return false;
  44385. }
  44386. }
  44387. }
  44388. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44389. // Bump texture cannot be not blocking.
  44390. if (!this._bumpTexture.isReady()) {
  44391. return false;
  44392. }
  44393. }
  44394. var refractionTexture = this._getRefractionTexture();
  44395. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44396. if (!refractionTexture.isReadyOrNotBlocking()) {
  44397. return false;
  44398. }
  44399. }
  44400. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44401. // This is blocking.
  44402. if (!this._environmentBRDFTexture.isReady()) {
  44403. return false;
  44404. }
  44405. }
  44406. }
  44407. }
  44408. if (defines._areImageProcessingDirty) {
  44409. if (!this._imageProcessingConfiguration.isReady()) {
  44410. return false;
  44411. }
  44412. }
  44413. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44414. mesh.createNormals(true);
  44415. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44416. }
  44417. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44418. if (effect) {
  44419. scene.resetCachedMaterial();
  44420. subMesh.setEffect(effect, defines);
  44421. this.buildUniformLayout();
  44422. }
  44423. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44424. return false;
  44425. }
  44426. defines._renderId = scene.getRenderId();
  44427. this._wasPreviouslyReady = true;
  44428. return true;
  44429. };
  44430. /**
  44431. * Specifies if the material uses metallic roughness workflow.
  44432. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44433. */
  44434. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44435. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44436. return true;
  44437. }
  44438. return false;
  44439. };
  44440. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44441. if (onCompiled === void 0) { onCompiled = null; }
  44442. if (onError === void 0) { onError = null; }
  44443. if (useInstances === void 0) { useInstances = null; }
  44444. if (useClipPlane === void 0) { useClipPlane = null; }
  44445. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44446. if (!defines.isDirty) {
  44447. return null;
  44448. }
  44449. defines.markAsProcessed();
  44450. var scene = this.getScene();
  44451. var engine = scene.getEngine();
  44452. // Fallbacks
  44453. var fallbacks = new BABYLON.EffectFallbacks();
  44454. var fallbackRank = 0;
  44455. if (defines.USESPHERICALINVERTEX) {
  44456. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44457. }
  44458. if (defines.FOG) {
  44459. fallbacks.addFallback(fallbackRank, "FOG");
  44460. }
  44461. if (defines.POINTSIZE) {
  44462. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44463. }
  44464. if (defines.LOGARITHMICDEPTH) {
  44465. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44466. }
  44467. if (defines.PARALLAX) {
  44468. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44469. }
  44470. if (defines.PARALLAXOCCLUSION) {
  44471. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44472. }
  44473. if (defines.ENVIRONMENTBRDF) {
  44474. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44475. }
  44476. if (defines.TANGENT) {
  44477. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44478. }
  44479. if (defines.BUMP) {
  44480. fallbacks.addFallback(fallbackRank++, "BUMP");
  44481. }
  44482. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44483. if (defines.SPECULARTERM) {
  44484. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44485. }
  44486. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44487. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44488. }
  44489. if (defines.LIGHTMAP) {
  44490. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44491. }
  44492. if (defines.NORMAL) {
  44493. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44494. }
  44495. if (defines.AMBIENT) {
  44496. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44497. }
  44498. if (defines.EMISSIVE) {
  44499. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44500. }
  44501. if (defines.VERTEXCOLOR) {
  44502. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44503. }
  44504. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44505. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44506. }
  44507. if (defines.MORPHTARGETS) {
  44508. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44509. }
  44510. //Attributes
  44511. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44512. if (defines.NORMAL) {
  44513. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44514. }
  44515. if (defines.TANGENT) {
  44516. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44517. }
  44518. if (defines.UV1) {
  44519. attribs.push(BABYLON.VertexBuffer.UVKind);
  44520. }
  44521. if (defines.UV2) {
  44522. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44523. }
  44524. if (defines.VERTEXCOLOR) {
  44525. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44526. }
  44527. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44528. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44529. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44530. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44531. "vFogInfos", "vFogColor", "pointSize",
  44532. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44533. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44534. "mBones",
  44535. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44536. "vLightingIntensity",
  44537. "logarithmicDepthConstant",
  44538. "vSphericalX", "vSphericalY", "vSphericalZ",
  44539. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44540. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44541. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44542. "vTangentSpaceParams"
  44543. ];
  44544. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44545. "bumpSampler", "lightmapSampler", "opacitySampler",
  44546. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44547. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44548. "microSurfaceSampler", "environmentBrdfSampler"];
  44549. var uniformBuffers = ["Material", "Scene"];
  44550. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44551. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44552. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44553. uniformsNames: uniforms,
  44554. uniformBuffersNames: uniformBuffers,
  44555. samplers: samplers,
  44556. defines: defines,
  44557. maxSimultaneousLights: this._maxSimultaneousLights
  44558. });
  44559. var join = defines.toString();
  44560. return engine.createEffect("pbr", {
  44561. attributes: attribs,
  44562. uniformsNames: uniforms,
  44563. uniformBuffersNames: uniformBuffers,
  44564. samplers: samplers,
  44565. defines: join,
  44566. fallbacks: fallbacks,
  44567. onCompiled: onCompiled,
  44568. onError: onError,
  44569. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44570. }, engine);
  44571. };
  44572. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44573. if (useInstances === void 0) { useInstances = null; }
  44574. if (useClipPlane === void 0) { useClipPlane = null; }
  44575. var scene = this.getScene();
  44576. var engine = scene.getEngine();
  44577. // Lights
  44578. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44579. defines._needNormals = true;
  44580. // Textures
  44581. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44582. if (defines._areTexturesDirty) {
  44583. defines._needUVs = false;
  44584. if (scene.texturesEnabled) {
  44585. if (scene.getEngine().getCaps().textureLOD) {
  44586. defines.LODBASEDMICROSFURACE = true;
  44587. }
  44588. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44589. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44590. }
  44591. else {
  44592. defines.ALBEDO = false;
  44593. }
  44594. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44595. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44596. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44597. }
  44598. else {
  44599. defines.AMBIENT = false;
  44600. }
  44601. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44602. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44603. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44604. }
  44605. else {
  44606. defines.OPACITY = false;
  44607. }
  44608. var reflectionTexture = this._getReflectionTexture();
  44609. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44610. defines.REFLECTION = true;
  44611. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44612. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44613. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44614. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44615. defines.INVERTCUBICMAP = true;
  44616. }
  44617. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44618. switch (reflectionTexture.coordinatesMode) {
  44619. case BABYLON.Texture.CUBIC_MODE:
  44620. case BABYLON.Texture.INVCUBIC_MODE:
  44621. defines.REFLECTIONMAP_CUBIC = true;
  44622. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44623. break;
  44624. case BABYLON.Texture.EXPLICIT_MODE:
  44625. defines.REFLECTIONMAP_EXPLICIT = true;
  44626. break;
  44627. case BABYLON.Texture.PLANAR_MODE:
  44628. defines.REFLECTIONMAP_PLANAR = true;
  44629. break;
  44630. case BABYLON.Texture.PROJECTION_MODE:
  44631. defines.REFLECTIONMAP_PROJECTION = true;
  44632. break;
  44633. case BABYLON.Texture.SKYBOX_MODE:
  44634. defines.REFLECTIONMAP_SKYBOX = true;
  44635. break;
  44636. case BABYLON.Texture.SPHERICAL_MODE:
  44637. defines.REFLECTIONMAP_SPHERICAL = true;
  44638. break;
  44639. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44640. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44641. break;
  44642. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44643. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44644. break;
  44645. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44646. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44647. break;
  44648. }
  44649. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44650. if (reflectionTexture.sphericalPolynomial) {
  44651. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44652. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44653. defines.USESPHERICALINVERTEX = false;
  44654. }
  44655. else {
  44656. defines.USESPHERICALINVERTEX = true;
  44657. }
  44658. }
  44659. }
  44660. }
  44661. else {
  44662. defines.REFLECTION = false;
  44663. defines.REFLECTIONMAP_3D = false;
  44664. defines.REFLECTIONMAP_SPHERICAL = false;
  44665. defines.REFLECTIONMAP_PLANAR = false;
  44666. defines.REFLECTIONMAP_CUBIC = false;
  44667. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44668. defines.REFLECTIONMAP_PROJECTION = false;
  44669. defines.REFLECTIONMAP_SKYBOX = false;
  44670. defines.REFLECTIONMAP_EXPLICIT = false;
  44671. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44672. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44673. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44674. defines.INVERTCUBICMAP = false;
  44675. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44676. defines.USESPHERICALINVERTEX = false;
  44677. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44678. defines.LODINREFLECTIONALPHA = false;
  44679. defines.GAMMAREFLECTION = false;
  44680. }
  44681. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44682. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44683. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44684. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44685. }
  44686. else {
  44687. defines.LIGHTMAP = false;
  44688. }
  44689. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44690. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44691. }
  44692. else {
  44693. defines.EMISSIVE = false;
  44694. }
  44695. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44696. if (this._metallicTexture) {
  44697. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44698. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44699. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44700. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44701. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44702. }
  44703. else if (this._reflectivityTexture) {
  44704. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44705. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44706. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44707. }
  44708. else {
  44709. defines.REFLECTIVITY = false;
  44710. }
  44711. if (this._microSurfaceTexture) {
  44712. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44713. }
  44714. else {
  44715. defines.MICROSURFACEMAP = false;
  44716. }
  44717. }
  44718. else {
  44719. defines.REFLECTIVITY = false;
  44720. defines.MICROSURFACEMAP = false;
  44721. }
  44722. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44723. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44724. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44725. defines.PARALLAX = true;
  44726. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44727. }
  44728. else {
  44729. defines.PARALLAX = false;
  44730. }
  44731. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44732. }
  44733. else {
  44734. defines.BUMP = false;
  44735. }
  44736. var refractionTexture = this._getRefractionTexture();
  44737. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44738. defines.REFRACTION = true;
  44739. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44740. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44741. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44742. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44743. if (this._linkRefractionWithTransparency) {
  44744. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44745. }
  44746. }
  44747. else {
  44748. defines.REFRACTION = false;
  44749. }
  44750. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44751. defines.ENVIRONMENTBRDF = true;
  44752. }
  44753. else {
  44754. defines.ENVIRONMENTBRDF = false;
  44755. }
  44756. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44757. defines.ALPHAFROMALBEDO = true;
  44758. }
  44759. else {
  44760. defines.ALPHAFROMALBEDO = false;
  44761. }
  44762. }
  44763. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44764. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44765. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44766. if (!this.backFaceCulling && this._twoSidedLighting) {
  44767. defines.TWOSIDEDLIGHTING = true;
  44768. }
  44769. else {
  44770. defines.TWOSIDEDLIGHTING = false;
  44771. }
  44772. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44773. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44774. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44775. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44776. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44777. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44778. }
  44779. if (defines._areImageProcessingDirty) {
  44780. this._imageProcessingConfiguration.prepareDefines(defines);
  44781. }
  44782. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44783. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44784. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44785. // Misc.
  44786. if (defines._areMiscDirty) {
  44787. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44788. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44789. }
  44790. // Values that need to be evaluated on every frame
  44791. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44792. // Attribs
  44793. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44794. };
  44795. /**
  44796. * Force shader compilation
  44797. */
  44798. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44799. var _this = this;
  44800. var localOptions = __assign({ clipPlane: false }, options);
  44801. var defines = new PBRMaterialDefines();
  44802. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44803. if (effect.isReady()) {
  44804. if (onCompiled) {
  44805. onCompiled(this);
  44806. }
  44807. }
  44808. else {
  44809. effect.onCompileObservable.add(function () {
  44810. if (onCompiled) {
  44811. onCompiled(_this);
  44812. }
  44813. });
  44814. }
  44815. };
  44816. /**
  44817. * Initializes the uniform buffer layout for the shader.
  44818. */
  44819. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44820. // Order is important !
  44821. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44822. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44823. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44824. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44825. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44826. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44827. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44828. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44829. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44830. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44831. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44832. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44833. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44834. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44835. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44836. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44837. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44838. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44839. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44840. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44841. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44842. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44843. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44844. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44845. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44846. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44847. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44848. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44849. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44850. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44851. this._uniformBuffer.addUniform("pointSize", 1);
  44852. this._uniformBuffer.create();
  44853. };
  44854. /**
  44855. * Unbinds the textures.
  44856. */
  44857. PBRBaseMaterial.prototype.unbind = function () {
  44858. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44859. this._uniformBuffer.setTexture("reflectionSampler", null);
  44860. }
  44861. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44862. this._uniformBuffer.setTexture("refractionSampler", null);
  44863. }
  44864. _super.prototype.unbind.call(this);
  44865. };
  44866. /**
  44867. * Binds the submesh data.
  44868. * @param world - The world matrix.
  44869. * @param mesh - The BJS mesh.
  44870. * @param subMesh - A submesh of the BJS mesh.
  44871. */
  44872. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44873. var scene = this.getScene();
  44874. var defines = subMesh._materialDefines;
  44875. if (!defines) {
  44876. return;
  44877. }
  44878. var effect = subMesh.effect;
  44879. if (!effect) {
  44880. return;
  44881. }
  44882. this._activeEffect = effect;
  44883. // Matrices
  44884. this.bindOnlyWorldMatrix(world);
  44885. // Normal Matrix
  44886. if (defines.OBJECTSPACE_NORMALMAP) {
  44887. world.toNormalMatrix(this._normalMatrix);
  44888. this.bindOnlyNormalMatrix(this._normalMatrix);
  44889. }
  44890. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44891. // Bones
  44892. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44893. var reflectionTexture = null;
  44894. if (mustRebind) {
  44895. this._uniformBuffer.bindToEffect(effect, "Material");
  44896. this.bindViewProjection(effect);
  44897. reflectionTexture = this._getReflectionTexture();
  44898. var refractionTexture = this._getRefractionTexture();
  44899. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44900. // Texture uniforms
  44901. if (scene.texturesEnabled) {
  44902. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44903. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44904. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44905. }
  44906. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44907. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44908. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44909. }
  44910. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44911. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44912. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44913. }
  44914. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44915. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44916. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44917. if (reflectionTexture.boundingBoxSize) {
  44918. var cubeTexture = reflectionTexture;
  44919. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44920. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44921. }
  44922. var polynomials = reflectionTexture.sphericalPolynomial;
  44923. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44924. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44925. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44926. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44927. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44928. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44929. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44930. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44931. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44932. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44933. }
  44934. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44935. }
  44936. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44937. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44938. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44939. }
  44940. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44941. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44942. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44943. }
  44944. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44945. if (this._metallicTexture) {
  44946. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44947. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44948. }
  44949. else if (this._reflectivityTexture) {
  44950. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44951. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44952. }
  44953. if (this._microSurfaceTexture) {
  44954. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44955. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44956. }
  44957. }
  44958. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44959. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44960. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44961. if (scene._mirroredCameraPosition) {
  44962. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44963. }
  44964. else {
  44965. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44966. }
  44967. }
  44968. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44969. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44970. var depth = 1.0;
  44971. if (!refractionTexture.isCube) {
  44972. if (refractionTexture.depth) {
  44973. depth = refractionTexture.depth;
  44974. }
  44975. }
  44976. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44977. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44978. }
  44979. }
  44980. // Point size
  44981. if (this.pointsCloud) {
  44982. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44983. }
  44984. // Colors
  44985. if (defines.METALLICWORKFLOW) {
  44986. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44987. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44988. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44989. }
  44990. else {
  44991. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44992. }
  44993. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44994. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44995. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44996. // Misc
  44997. this._lightingInfos.x = this._directIntensity;
  44998. this._lightingInfos.y = this._emissiveIntensity;
  44999. this._lightingInfos.z = this._environmentIntensity;
  45000. this._lightingInfos.w = this._specularIntensity;
  45001. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45002. }
  45003. // Textures
  45004. if (scene.texturesEnabled) {
  45005. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45006. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45007. }
  45008. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45009. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45010. }
  45011. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45012. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45013. }
  45014. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45015. if (defines.LODBASEDMICROSFURACE) {
  45016. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45017. }
  45018. else {
  45019. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45020. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45021. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45022. }
  45023. }
  45024. if (defines.ENVIRONMENTBRDF) {
  45025. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45026. }
  45027. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45028. if (defines.LODBASEDMICROSFURACE) {
  45029. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45030. }
  45031. else {
  45032. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45033. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45034. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45035. }
  45036. }
  45037. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45038. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45039. }
  45040. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45041. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45042. }
  45043. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45044. if (this._metallicTexture) {
  45045. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45046. }
  45047. else if (this._reflectivityTexture) {
  45048. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45049. }
  45050. if (this._microSurfaceTexture) {
  45051. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45052. }
  45053. }
  45054. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45055. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45056. }
  45057. }
  45058. // Clip plane
  45059. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45060. // Colors
  45061. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45062. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45063. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45064. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45065. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45066. }
  45067. if (mustRebind || !this.isFrozen) {
  45068. // Lights
  45069. if (scene.lightsEnabled && !this._disableLighting) {
  45070. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45071. }
  45072. // View
  45073. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45074. this.bindView(effect);
  45075. }
  45076. // Fog
  45077. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45078. // Morph targets
  45079. if (defines.NUM_MORPH_INFLUENCERS) {
  45080. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45081. }
  45082. // image processing
  45083. this._imageProcessingConfiguration.bind(this._activeEffect);
  45084. // Log. depth
  45085. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45086. }
  45087. this._uniformBuffer.update();
  45088. this._afterBind(mesh);
  45089. };
  45090. /**
  45091. * Returns the animatable textures.
  45092. * @returns - Array of animatable textures.
  45093. */
  45094. PBRBaseMaterial.prototype.getAnimatables = function () {
  45095. var results = [];
  45096. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45097. results.push(this._albedoTexture);
  45098. }
  45099. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45100. results.push(this._ambientTexture);
  45101. }
  45102. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45103. results.push(this._opacityTexture);
  45104. }
  45105. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45106. results.push(this._reflectionTexture);
  45107. }
  45108. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45109. results.push(this._emissiveTexture);
  45110. }
  45111. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45112. results.push(this._metallicTexture);
  45113. }
  45114. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45115. results.push(this._reflectivityTexture);
  45116. }
  45117. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45118. results.push(this._bumpTexture);
  45119. }
  45120. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45121. results.push(this._lightmapTexture);
  45122. }
  45123. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45124. results.push(this._refractionTexture);
  45125. }
  45126. return results;
  45127. };
  45128. /**
  45129. * Returns the texture used for reflections.
  45130. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45131. */
  45132. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45133. if (this._reflectionTexture) {
  45134. return this._reflectionTexture;
  45135. }
  45136. return this.getScene().environmentTexture;
  45137. };
  45138. /**
  45139. * Returns the texture used for refraction or null if none is used.
  45140. * @returns - Refection texture if present. If no refraction texture and refraction
  45141. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45142. */
  45143. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45144. if (this._refractionTexture) {
  45145. return this._refractionTexture;
  45146. }
  45147. if (this._linkRefractionWithTransparency) {
  45148. return this.getScene().environmentTexture;
  45149. }
  45150. return null;
  45151. };
  45152. /**
  45153. * Disposes the resources of the material.
  45154. * @param forceDisposeEffect - Forces the disposal of effects.
  45155. * @param forceDisposeTextures - Forces the disposal of all textures.
  45156. */
  45157. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45158. if (forceDisposeTextures) {
  45159. if (this._albedoTexture) {
  45160. this._albedoTexture.dispose();
  45161. }
  45162. if (this._ambientTexture) {
  45163. this._ambientTexture.dispose();
  45164. }
  45165. if (this._opacityTexture) {
  45166. this._opacityTexture.dispose();
  45167. }
  45168. if (this._reflectionTexture) {
  45169. this._reflectionTexture.dispose();
  45170. }
  45171. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45172. this._environmentBRDFTexture.dispose();
  45173. }
  45174. if (this._emissiveTexture) {
  45175. this._emissiveTexture.dispose();
  45176. }
  45177. if (this._metallicTexture) {
  45178. this._metallicTexture.dispose();
  45179. }
  45180. if (this._reflectivityTexture) {
  45181. this._reflectivityTexture.dispose();
  45182. }
  45183. if (this._bumpTexture) {
  45184. this._bumpTexture.dispose();
  45185. }
  45186. if (this._lightmapTexture) {
  45187. this._lightmapTexture.dispose();
  45188. }
  45189. if (this._refractionTexture) {
  45190. this._refractionTexture.dispose();
  45191. }
  45192. }
  45193. this._renderTargets.dispose();
  45194. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45195. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45196. }
  45197. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45198. };
  45199. /**
  45200. * Stores the reflectivity values based on metallic roughness workflow.
  45201. */
  45202. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45203. __decorate([
  45204. BABYLON.serializeAsImageProcessingConfiguration()
  45205. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45206. __decorate([
  45207. BABYLON.serialize()
  45208. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45209. __decorate([
  45210. BABYLON.serialize()
  45211. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45212. return PBRBaseMaterial;
  45213. }(BABYLON.PushMaterial));
  45214. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45215. })(BABYLON || (BABYLON = {}));
  45216. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45217. "use strict";
  45218. var BABYLON;
  45219. (function (BABYLON) {
  45220. /**
  45221. * The Physically based simple base material of BJS.
  45222. *
  45223. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45224. * It is used as the base class for both the specGloss and metalRough conventions.
  45225. */
  45226. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45227. __extends(PBRBaseSimpleMaterial, _super);
  45228. /**
  45229. * Instantiates a new PBRMaterial instance.
  45230. *
  45231. * @param name The material name
  45232. * @param scene The scene the material will be use in.
  45233. */
  45234. function PBRBaseSimpleMaterial(name, scene) {
  45235. var _this = _super.call(this, name, scene) || this;
  45236. /**
  45237. * Number of Simultaneous lights allowed on the material.
  45238. */
  45239. _this.maxSimultaneousLights = 4;
  45240. /**
  45241. * If sets to true, disables all the lights affecting the material.
  45242. */
  45243. _this.disableLighting = false;
  45244. /**
  45245. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45246. */
  45247. _this.invertNormalMapX = false;
  45248. /**
  45249. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45250. */
  45251. _this.invertNormalMapY = false;
  45252. /**
  45253. * Emissivie color used to self-illuminate the model.
  45254. */
  45255. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45256. /**
  45257. * Occlusion Channel Strenght.
  45258. */
  45259. _this.occlusionStrength = 1.0;
  45260. _this.useLightmapAsShadowmap = false;
  45261. _this._useAlphaFromAlbedoTexture = true;
  45262. _this._useAmbientInGrayScale = true;
  45263. return _this;
  45264. }
  45265. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45266. /**
  45267. * Gets the current double sided mode.
  45268. */
  45269. get: function () {
  45270. return this._twoSidedLighting;
  45271. },
  45272. /**
  45273. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45274. */
  45275. set: function (value) {
  45276. if (this._twoSidedLighting === value) {
  45277. return;
  45278. }
  45279. this._twoSidedLighting = value;
  45280. this.backFaceCulling = !value;
  45281. this._markAllSubMeshesAsTexturesDirty();
  45282. },
  45283. enumerable: true,
  45284. configurable: true
  45285. });
  45286. /**
  45287. * Return the active textures of the material.
  45288. */
  45289. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45290. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45291. if (this.environmentTexture) {
  45292. activeTextures.push(this.environmentTexture);
  45293. }
  45294. if (this.normalTexture) {
  45295. activeTextures.push(this.normalTexture);
  45296. }
  45297. if (this.emissiveTexture) {
  45298. activeTextures.push(this.emissiveTexture);
  45299. }
  45300. if (this.occlusionTexture) {
  45301. activeTextures.push(this.occlusionTexture);
  45302. }
  45303. if (this.lightmapTexture) {
  45304. activeTextures.push(this.lightmapTexture);
  45305. }
  45306. return activeTextures;
  45307. };
  45308. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45309. if (_super.prototype.hasTexture.call(this, texture)) {
  45310. return true;
  45311. }
  45312. if (this.lightmapTexture === texture) {
  45313. return true;
  45314. }
  45315. return false;
  45316. };
  45317. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45318. return "PBRBaseSimpleMaterial";
  45319. };
  45320. __decorate([
  45321. BABYLON.serialize(),
  45322. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45323. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45324. __decorate([
  45325. BABYLON.serialize(),
  45326. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45327. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45328. __decorate([
  45329. BABYLON.serializeAsTexture(),
  45330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45331. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45332. __decorate([
  45333. BABYLON.serialize(),
  45334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45335. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45336. __decorate([
  45337. BABYLON.serialize(),
  45338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45339. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45340. __decorate([
  45341. BABYLON.serializeAsTexture(),
  45342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45343. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45344. __decorate([
  45345. BABYLON.serializeAsColor3("emissive"),
  45346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45347. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45348. __decorate([
  45349. BABYLON.serializeAsTexture(),
  45350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45351. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45352. __decorate([
  45353. BABYLON.serialize(),
  45354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45355. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45356. __decorate([
  45357. BABYLON.serializeAsTexture(),
  45358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45359. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45360. __decorate([
  45361. BABYLON.serialize(),
  45362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45363. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45364. __decorate([
  45365. BABYLON.serialize()
  45366. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45367. __decorate([
  45368. BABYLON.serializeAsTexture(),
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45370. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45371. __decorate([
  45372. BABYLON.serialize(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45374. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45375. return PBRBaseSimpleMaterial;
  45376. }(BABYLON.PBRBaseMaterial));
  45377. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45378. })(BABYLON || (BABYLON = {}));
  45379. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45380. "use strict";
  45381. var BABYLON;
  45382. (function (BABYLON) {
  45383. /**
  45384. * The Physically based material of BJS.
  45385. *
  45386. * This offers the main features of a standard PBR material.
  45387. * For more information, please refer to the documentation :
  45388. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45389. */
  45390. var PBRMaterial = /** @class */ (function (_super) {
  45391. __extends(PBRMaterial, _super);
  45392. /**
  45393. * Instantiates a new PBRMaterial instance.
  45394. *
  45395. * @param name The material name
  45396. * @param scene The scene the material will be use in.
  45397. */
  45398. function PBRMaterial(name, scene) {
  45399. var _this = _super.call(this, name, scene) || this;
  45400. /**
  45401. * Intensity of the direct lights e.g. the four lights available in your scene.
  45402. * This impacts both the direct diffuse and specular highlights.
  45403. */
  45404. _this.directIntensity = 1.0;
  45405. /**
  45406. * Intensity of the emissive part of the material.
  45407. * This helps controlling the emissive effect without modifying the emissive color.
  45408. */
  45409. _this.emissiveIntensity = 1.0;
  45410. /**
  45411. * Intensity of the environment e.g. how much the environment will light the object
  45412. * either through harmonics for rough material or through the refelction for shiny ones.
  45413. */
  45414. _this.environmentIntensity = 1.0;
  45415. /**
  45416. * This is a special control allowing the reduction of the specular highlights coming from the
  45417. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45418. */
  45419. _this.specularIntensity = 1.0;
  45420. /**
  45421. * Debug Control allowing disabling the bump map on this material.
  45422. */
  45423. _this.disableBumpMap = false;
  45424. /**
  45425. * AKA Occlusion Texture Intensity in other nomenclature.
  45426. */
  45427. _this.ambientTextureStrength = 1.0;
  45428. /**
  45429. * The color of a material in ambient lighting.
  45430. */
  45431. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45432. /**
  45433. * AKA Diffuse Color in other nomenclature.
  45434. */
  45435. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45436. /**
  45437. * AKA Specular Color in other nomenclature.
  45438. */
  45439. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45440. /**
  45441. * The color reflected from the material.
  45442. */
  45443. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45444. /**
  45445. * The color emitted from the material.
  45446. */
  45447. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45448. /**
  45449. * AKA Glossiness in other nomenclature.
  45450. */
  45451. _this.microSurface = 1.0;
  45452. /**
  45453. * source material index of refraction (IOR)' / 'destination material IOR.
  45454. */
  45455. _this.indexOfRefraction = 0.66;
  45456. /**
  45457. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45458. */
  45459. _this.invertRefractionY = false;
  45460. /**
  45461. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45462. * Materials half opaque for instance using refraction could benefit from this control.
  45463. */
  45464. _this.linkRefractionWithTransparency = false;
  45465. _this.useLightmapAsShadowmap = false;
  45466. /**
  45467. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45468. */
  45469. _this.useAlphaFromAlbedoTexture = false;
  45470. /**
  45471. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45472. */
  45473. _this.forceAlphaTest = false;
  45474. /**
  45475. * Defines the alpha limits in alpha test mode.
  45476. */
  45477. _this.alphaCutOff = 0.4;
  45478. /**
  45479. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45480. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45481. */
  45482. _this.useSpecularOverAlpha = true;
  45483. /**
  45484. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45485. */
  45486. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45487. /**
  45488. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45489. */
  45490. _this.useRoughnessFromMetallicTextureAlpha = true;
  45491. /**
  45492. * Specifies if the metallic texture contains the roughness information in its green channel.
  45493. */
  45494. _this.useRoughnessFromMetallicTextureGreen = false;
  45495. /**
  45496. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45497. */
  45498. _this.useMetallnessFromMetallicTextureBlue = false;
  45499. /**
  45500. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45501. */
  45502. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45503. /**
  45504. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45505. */
  45506. _this.useAmbientInGrayScale = false;
  45507. /**
  45508. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45509. * The material will try to infer what glossiness each pixel should be.
  45510. */
  45511. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45512. /**
  45513. * BJS is using an harcoded light falloff based on a manually sets up range.
  45514. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45515. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45516. */
  45517. _this.usePhysicalLightFalloff = true;
  45518. /**
  45519. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45520. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45521. */
  45522. _this.useRadianceOverAlpha = true;
  45523. /**
  45524. * Allows using an object space normal map (instead of tangent space).
  45525. */
  45526. _this.useObjectSpaceNormalMap = false;
  45527. /**
  45528. * Allows using the bump map in parallax mode.
  45529. */
  45530. _this.useParallax = false;
  45531. /**
  45532. * Allows using the bump map in parallax occlusion mode.
  45533. */
  45534. _this.useParallaxOcclusion = false;
  45535. /**
  45536. * Controls the scale bias of the parallax mode.
  45537. */
  45538. _this.parallaxScaleBias = 0.05;
  45539. /**
  45540. * If sets to true, disables all the lights affecting the material.
  45541. */
  45542. _this.disableLighting = false;
  45543. /**
  45544. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45545. */
  45546. _this.forceIrradianceInFragment = false;
  45547. /**
  45548. * Number of Simultaneous lights allowed on the material.
  45549. */
  45550. _this.maxSimultaneousLights = 4;
  45551. /**
  45552. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45553. */
  45554. _this.invertNormalMapX = false;
  45555. /**
  45556. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45557. */
  45558. _this.invertNormalMapY = false;
  45559. /**
  45560. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45561. */
  45562. _this.twoSidedLighting = false;
  45563. /**
  45564. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45565. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45566. */
  45567. _this.useAlphaFresnel = false;
  45568. /**
  45569. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45570. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45571. */
  45572. _this.useLinearAlphaFresnel = false;
  45573. /**
  45574. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45575. * And/Or occlude the blended part.
  45576. */
  45577. _this.environmentBRDFTexture = null;
  45578. /**
  45579. * Force normal to face away from face.
  45580. */
  45581. _this.forceNormalForward = false;
  45582. /**
  45583. * Enables specular anti aliasing in the PBR shader.
  45584. * It will both interacts on the Geometry for analytical and IBL lighting.
  45585. * It also prefilter the roughness map based on the bump values.
  45586. */
  45587. _this.enableSpecularAntiAliasing = false;
  45588. /**
  45589. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45590. * makes the reflect vector face the model (under horizon).
  45591. */
  45592. _this.useHorizonOcclusion = true;
  45593. /**
  45594. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45595. * too much the area relying on ambient texture to define their ambient occlusion.
  45596. */
  45597. _this.useRadianceOcclusion = true;
  45598. /**
  45599. * If set to true, no lighting calculations will be applied.
  45600. */
  45601. _this.unlit = false;
  45602. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45603. return _this;
  45604. }
  45605. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45606. /**
  45607. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45608. */
  45609. get: function () {
  45610. return this._PBRMATERIAL_OPAQUE;
  45611. },
  45612. enumerable: true,
  45613. configurable: true
  45614. });
  45615. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45616. /**
  45617. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45618. */
  45619. get: function () {
  45620. return this._PBRMATERIAL_ALPHATEST;
  45621. },
  45622. enumerable: true,
  45623. configurable: true
  45624. });
  45625. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45626. /**
  45627. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45628. */
  45629. get: function () {
  45630. return this._PBRMATERIAL_ALPHABLEND;
  45631. },
  45632. enumerable: true,
  45633. configurable: true
  45634. });
  45635. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45636. /**
  45637. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45638. * They are also discarded below the alpha cutoff threshold to improve performances.
  45639. */
  45640. get: function () {
  45641. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45642. },
  45643. enumerable: true,
  45644. configurable: true
  45645. });
  45646. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45647. /**
  45648. * Gets the image processing configuration used either in this material.
  45649. */
  45650. get: function () {
  45651. return this._imageProcessingConfiguration;
  45652. },
  45653. /**
  45654. * Sets the Default image processing configuration used either in the this material.
  45655. *
  45656. * If sets to null, the scene one is in use.
  45657. */
  45658. set: function (value) {
  45659. this._attachImageProcessingConfiguration(value);
  45660. // Ensure the effect will be rebuilt.
  45661. this._markAllSubMeshesAsTexturesDirty();
  45662. },
  45663. enumerable: true,
  45664. configurable: true
  45665. });
  45666. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45667. /**
  45668. * Gets wether the color curves effect is enabled.
  45669. */
  45670. get: function () {
  45671. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45672. },
  45673. /**
  45674. * Sets wether the color curves effect is enabled.
  45675. */
  45676. set: function (value) {
  45677. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45678. },
  45679. enumerable: true,
  45680. configurable: true
  45681. });
  45682. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45683. /**
  45684. * Gets wether the color grading effect is enabled.
  45685. */
  45686. get: function () {
  45687. return this.imageProcessingConfiguration.colorGradingEnabled;
  45688. },
  45689. /**
  45690. * Gets wether the color grading effect is enabled.
  45691. */
  45692. set: function (value) {
  45693. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45694. },
  45695. enumerable: true,
  45696. configurable: true
  45697. });
  45698. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45699. /**
  45700. * Gets wether tonemapping is enabled or not.
  45701. */
  45702. get: function () {
  45703. return this._imageProcessingConfiguration.toneMappingEnabled;
  45704. },
  45705. /**
  45706. * Sets wether tonemapping is enabled or not
  45707. */
  45708. set: function (value) {
  45709. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45710. },
  45711. enumerable: true,
  45712. configurable: true
  45713. });
  45714. ;
  45715. ;
  45716. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45717. /**
  45718. * The camera exposure used on this material.
  45719. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45720. * This corresponds to a photographic exposure.
  45721. */
  45722. get: function () {
  45723. return this._imageProcessingConfiguration.exposure;
  45724. },
  45725. /**
  45726. * The camera exposure used on this material.
  45727. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45728. * This corresponds to a photographic exposure.
  45729. */
  45730. set: function (value) {
  45731. this._imageProcessingConfiguration.exposure = value;
  45732. },
  45733. enumerable: true,
  45734. configurable: true
  45735. });
  45736. ;
  45737. ;
  45738. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45739. /**
  45740. * Gets The camera contrast used on this material.
  45741. */
  45742. get: function () {
  45743. return this._imageProcessingConfiguration.contrast;
  45744. },
  45745. /**
  45746. * Sets The camera contrast used on this material.
  45747. */
  45748. set: function (value) {
  45749. this._imageProcessingConfiguration.contrast = value;
  45750. },
  45751. enumerable: true,
  45752. configurable: true
  45753. });
  45754. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45755. /**
  45756. * Gets the Color Grading 2D Lookup Texture.
  45757. */
  45758. get: function () {
  45759. return this._imageProcessingConfiguration.colorGradingTexture;
  45760. },
  45761. /**
  45762. * Sets the Color Grading 2D Lookup Texture.
  45763. */
  45764. set: function (value) {
  45765. this._imageProcessingConfiguration.colorGradingTexture = value;
  45766. },
  45767. enumerable: true,
  45768. configurable: true
  45769. });
  45770. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45771. /**
  45772. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45773. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45774. * 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;
  45775. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45776. */
  45777. get: function () {
  45778. return this._imageProcessingConfiguration.colorCurves;
  45779. },
  45780. /**
  45781. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45782. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45783. * 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;
  45784. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45785. */
  45786. set: function (value) {
  45787. this._imageProcessingConfiguration.colorCurves = value;
  45788. },
  45789. enumerable: true,
  45790. configurable: true
  45791. });
  45792. /**
  45793. * Returns the name of this material class.
  45794. */
  45795. PBRMaterial.prototype.getClassName = function () {
  45796. return "PBRMaterial";
  45797. };
  45798. /**
  45799. * Returns an array of the actively used textures.
  45800. * @returns - Array of BaseTextures
  45801. */
  45802. PBRMaterial.prototype.getActiveTextures = function () {
  45803. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45804. if (this._albedoTexture) {
  45805. activeTextures.push(this._albedoTexture);
  45806. }
  45807. if (this._ambientTexture) {
  45808. activeTextures.push(this._ambientTexture);
  45809. }
  45810. if (this._opacityTexture) {
  45811. activeTextures.push(this._opacityTexture);
  45812. }
  45813. if (this._reflectionTexture) {
  45814. activeTextures.push(this._reflectionTexture);
  45815. }
  45816. if (this._emissiveTexture) {
  45817. activeTextures.push(this._emissiveTexture);
  45818. }
  45819. if (this._reflectivityTexture) {
  45820. activeTextures.push(this._reflectivityTexture);
  45821. }
  45822. if (this._metallicTexture) {
  45823. activeTextures.push(this._metallicTexture);
  45824. }
  45825. if (this._microSurfaceTexture) {
  45826. activeTextures.push(this._microSurfaceTexture);
  45827. }
  45828. if (this._bumpTexture) {
  45829. activeTextures.push(this._bumpTexture);
  45830. }
  45831. if (this._lightmapTexture) {
  45832. activeTextures.push(this._lightmapTexture);
  45833. }
  45834. if (this._refractionTexture) {
  45835. activeTextures.push(this._refractionTexture);
  45836. }
  45837. return activeTextures;
  45838. };
  45839. /**
  45840. * Checks to see if a texture is used in the material.
  45841. * @param texture - Base texture to use.
  45842. * @returns - Boolean specifying if a texture is used in the material.
  45843. */
  45844. PBRMaterial.prototype.hasTexture = function (texture) {
  45845. if (_super.prototype.hasTexture.call(this, texture)) {
  45846. return true;
  45847. }
  45848. if (this._albedoTexture === texture) {
  45849. return true;
  45850. }
  45851. if (this._ambientTexture === texture) {
  45852. return true;
  45853. }
  45854. if (this._opacityTexture === texture) {
  45855. return true;
  45856. }
  45857. if (this._reflectionTexture === texture) {
  45858. return true;
  45859. }
  45860. if (this._reflectivityTexture === texture) {
  45861. return true;
  45862. }
  45863. if (this._metallicTexture === texture) {
  45864. return true;
  45865. }
  45866. if (this._microSurfaceTexture === texture) {
  45867. return true;
  45868. }
  45869. if (this._bumpTexture === texture) {
  45870. return true;
  45871. }
  45872. if (this._lightmapTexture === texture) {
  45873. return true;
  45874. }
  45875. if (this._refractionTexture === texture) {
  45876. return true;
  45877. }
  45878. return false;
  45879. };
  45880. /**
  45881. * Makes a duplicate of the current material.
  45882. * @param name - name to use for the new material.
  45883. */
  45884. PBRMaterial.prototype.clone = function (name) {
  45885. var _this = this;
  45886. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45887. clone.id = name;
  45888. clone.name = name;
  45889. return clone;
  45890. };
  45891. /**
  45892. * Serializes this PBR Material.
  45893. * @returns - An object with the serialized material.
  45894. */
  45895. PBRMaterial.prototype.serialize = function () {
  45896. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45897. serializationObject.customType = "BABYLON.PBRMaterial";
  45898. return serializationObject;
  45899. };
  45900. // Statics
  45901. /**
  45902. * Parses a PBR Material from a serialized object.
  45903. * @param source - Serialized object.
  45904. * @param scene - BJS scene instance.
  45905. * @param rootUrl - url for the scene object
  45906. * @returns - PBRMaterial
  45907. */
  45908. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45909. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45910. };
  45911. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45912. /**
  45913. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45914. */
  45915. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45916. /**
  45917. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45918. */
  45919. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45920. /**
  45921. * 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.
  45922. * They are also discarded below the alpha cutoff threshold to improve performances.
  45923. */
  45924. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45925. __decorate([
  45926. BABYLON.serialize(),
  45927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45928. ], PBRMaterial.prototype, "directIntensity", void 0);
  45929. __decorate([
  45930. BABYLON.serialize(),
  45931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45932. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45933. __decorate([
  45934. BABYLON.serialize(),
  45935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45936. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45937. __decorate([
  45938. BABYLON.serialize(),
  45939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45940. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45941. __decorate([
  45942. BABYLON.serialize(),
  45943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45944. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45945. __decorate([
  45946. BABYLON.serializeAsTexture(),
  45947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45948. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45949. __decorate([
  45950. BABYLON.serializeAsTexture(),
  45951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45952. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45953. __decorate([
  45954. BABYLON.serialize(),
  45955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45956. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45957. __decorate([
  45958. BABYLON.serializeAsTexture(),
  45959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45960. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45961. __decorate([
  45962. BABYLON.serializeAsTexture(),
  45963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45964. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45965. __decorate([
  45966. BABYLON.serializeAsTexture(),
  45967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45968. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45969. __decorate([
  45970. BABYLON.serializeAsTexture(),
  45971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45972. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45973. __decorate([
  45974. BABYLON.serializeAsTexture(),
  45975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45976. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45977. __decorate([
  45978. BABYLON.serialize(),
  45979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45980. ], PBRMaterial.prototype, "metallic", void 0);
  45981. __decorate([
  45982. BABYLON.serialize(),
  45983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45984. ], PBRMaterial.prototype, "roughness", void 0);
  45985. __decorate([
  45986. BABYLON.serializeAsTexture(),
  45987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45988. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45989. __decorate([
  45990. BABYLON.serializeAsTexture(),
  45991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45992. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45993. __decorate([
  45994. BABYLON.serializeAsTexture(),
  45995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45996. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45997. __decorate([
  45998. BABYLON.serializeAsTexture(),
  45999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46000. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46001. __decorate([
  46002. BABYLON.serializeAsColor3("ambient"),
  46003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46004. ], PBRMaterial.prototype, "ambientColor", void 0);
  46005. __decorate([
  46006. BABYLON.serializeAsColor3("albedo"),
  46007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46008. ], PBRMaterial.prototype, "albedoColor", void 0);
  46009. __decorate([
  46010. BABYLON.serializeAsColor3("reflectivity"),
  46011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46012. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46013. __decorate([
  46014. BABYLON.serializeAsColor3("reflection"),
  46015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46016. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46017. __decorate([
  46018. BABYLON.serializeAsColor3("emissive"),
  46019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46020. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46021. __decorate([
  46022. BABYLON.serialize(),
  46023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46024. ], PBRMaterial.prototype, "microSurface", void 0);
  46025. __decorate([
  46026. BABYLON.serialize(),
  46027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46028. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46029. __decorate([
  46030. BABYLON.serialize(),
  46031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46032. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46033. __decorate([
  46034. BABYLON.serialize(),
  46035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46036. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46037. __decorate([
  46038. BABYLON.serialize(),
  46039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46040. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46041. __decorate([
  46042. BABYLON.serialize(),
  46043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46044. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46045. __decorate([
  46046. BABYLON.serialize(),
  46047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46048. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46049. __decorate([
  46050. BABYLON.serialize(),
  46051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46052. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46053. __decorate([
  46054. BABYLON.serialize(),
  46055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46056. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46057. __decorate([
  46058. BABYLON.serialize(),
  46059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46060. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46061. __decorate([
  46062. BABYLON.serialize(),
  46063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46064. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46065. __decorate([
  46066. BABYLON.serialize(),
  46067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46068. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46069. __decorate([
  46070. BABYLON.serialize(),
  46071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46072. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46073. __decorate([
  46074. BABYLON.serialize(),
  46075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46076. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46077. __decorate([
  46078. BABYLON.serialize(),
  46079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46080. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46081. __decorate([
  46082. BABYLON.serialize(),
  46083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46084. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46085. __decorate([
  46086. BABYLON.serialize(),
  46087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46088. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46089. __decorate([
  46090. BABYLON.serialize(),
  46091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46092. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46093. __decorate([
  46094. BABYLON.serialize(),
  46095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46096. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46097. __decorate([
  46098. BABYLON.serialize(),
  46099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46100. ], PBRMaterial.prototype, "useParallax", void 0);
  46101. __decorate([
  46102. BABYLON.serialize(),
  46103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46104. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46105. __decorate([
  46106. BABYLON.serialize(),
  46107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46108. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46109. __decorate([
  46110. BABYLON.serialize(),
  46111. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46112. ], PBRMaterial.prototype, "disableLighting", void 0);
  46113. __decorate([
  46114. BABYLON.serialize(),
  46115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46116. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46117. __decorate([
  46118. BABYLON.serialize(),
  46119. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46120. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46121. __decorate([
  46122. BABYLON.serialize(),
  46123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46124. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46125. __decorate([
  46126. BABYLON.serialize(),
  46127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46128. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46129. __decorate([
  46130. BABYLON.serialize(),
  46131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46132. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46133. __decorate([
  46134. BABYLON.serialize(),
  46135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46136. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46137. __decorate([
  46138. BABYLON.serialize(),
  46139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46140. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46141. __decorate([
  46142. BABYLON.serializeAsTexture(),
  46143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46144. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46145. __decorate([
  46146. BABYLON.serialize(),
  46147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46148. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46149. __decorate([
  46150. BABYLON.serialize(),
  46151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46152. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46153. __decorate([
  46154. BABYLON.serialize(),
  46155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46156. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46157. __decorate([
  46158. BABYLON.serialize(),
  46159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46160. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46161. __decorate([
  46162. BABYLON.serialize(),
  46163. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46164. ], PBRMaterial.prototype, "unlit", void 0);
  46165. return PBRMaterial;
  46166. }(BABYLON.PBRBaseMaterial));
  46167. BABYLON.PBRMaterial = PBRMaterial;
  46168. })(BABYLON || (BABYLON = {}));
  46169. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46170. "use strict";
  46171. var BABYLON;
  46172. (function (BABYLON) {
  46173. /**
  46174. * The PBR material of BJS following the metal roughness convention.
  46175. *
  46176. * This fits to the PBR convention in the GLTF definition:
  46177. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46178. */
  46179. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46180. __extends(PBRMetallicRoughnessMaterial, _super);
  46181. /**
  46182. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46183. *
  46184. * @param name The material name
  46185. * @param scene The scene the material will be use in.
  46186. */
  46187. function PBRMetallicRoughnessMaterial(name, scene) {
  46188. var _this = _super.call(this, name, scene) || this;
  46189. _this._useRoughnessFromMetallicTextureAlpha = false;
  46190. _this._useRoughnessFromMetallicTextureGreen = true;
  46191. _this._useMetallnessFromMetallicTextureBlue = true;
  46192. _this.metallic = 1.0;
  46193. _this.roughness = 1.0;
  46194. return _this;
  46195. }
  46196. /**
  46197. * Return the currrent class name of the material.
  46198. */
  46199. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46200. return "PBRMetallicRoughnessMaterial";
  46201. };
  46202. /**
  46203. * Return the active textures of the material.
  46204. */
  46205. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46206. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46207. if (this.baseTexture) {
  46208. activeTextures.push(this.baseTexture);
  46209. }
  46210. if (this.metallicRoughnessTexture) {
  46211. activeTextures.push(this.metallicRoughnessTexture);
  46212. }
  46213. return activeTextures;
  46214. };
  46215. /**
  46216. * Checks to see if a texture is used in the material.
  46217. * @param texture - Base texture to use.
  46218. * @returns - Boolean specifying if a texture is used in the material.
  46219. */
  46220. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46221. if (_super.prototype.hasTexture.call(this, texture)) {
  46222. return true;
  46223. }
  46224. if (this.baseTexture === texture) {
  46225. return true;
  46226. }
  46227. if (this.metallicRoughnessTexture === texture) {
  46228. return true;
  46229. }
  46230. return false;
  46231. };
  46232. /**
  46233. * Makes a duplicate of the current material.
  46234. * @param name - name to use for the new material.
  46235. */
  46236. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46237. var _this = this;
  46238. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46239. clone.id = name;
  46240. clone.name = name;
  46241. return clone;
  46242. };
  46243. /**
  46244. * Serialize the material to a parsable JSON object.
  46245. */
  46246. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46247. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46248. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46249. return serializationObject;
  46250. };
  46251. /**
  46252. * Parses a JSON object correponding to the serialize function.
  46253. */
  46254. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46255. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46256. };
  46257. __decorate([
  46258. BABYLON.serializeAsColor3(),
  46259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46260. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46261. __decorate([
  46262. BABYLON.serializeAsTexture(),
  46263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46264. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46265. __decorate([
  46266. BABYLON.serialize(),
  46267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46268. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46269. __decorate([
  46270. BABYLON.serialize(),
  46271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46272. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46273. __decorate([
  46274. BABYLON.serializeAsTexture(),
  46275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46276. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46277. return PBRMetallicRoughnessMaterial;
  46278. }(BABYLON.PBRBaseSimpleMaterial));
  46279. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46280. })(BABYLON || (BABYLON = {}));
  46281. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46282. "use strict";
  46283. var BABYLON;
  46284. (function (BABYLON) {
  46285. /**
  46286. * The PBR material of BJS following the specular glossiness convention.
  46287. *
  46288. * This fits to the PBR convention in the GLTF definition:
  46289. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46290. */
  46291. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46292. __extends(PBRSpecularGlossinessMaterial, _super);
  46293. /**
  46294. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46295. *
  46296. * @param name The material name
  46297. * @param scene The scene the material will be use in.
  46298. */
  46299. function PBRSpecularGlossinessMaterial(name, scene) {
  46300. var _this = _super.call(this, name, scene) || this;
  46301. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46302. return _this;
  46303. }
  46304. /**
  46305. * Return the currrent class name of the material.
  46306. */
  46307. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46308. return "PBRSpecularGlossinessMaterial";
  46309. };
  46310. /**
  46311. * Return the active textures of the material.
  46312. */
  46313. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46314. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46315. if (this.diffuseTexture) {
  46316. activeTextures.push(this.diffuseTexture);
  46317. }
  46318. if (this.specularGlossinessTexture) {
  46319. activeTextures.push(this.specularGlossinessTexture);
  46320. }
  46321. return activeTextures;
  46322. };
  46323. /**
  46324. * Checks to see if a texture is used in the material.
  46325. * @param texture - Base texture to use.
  46326. * @returns - Boolean specifying if a texture is used in the material.
  46327. */
  46328. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46329. if (_super.prototype.hasTexture.call(this, texture)) {
  46330. return true;
  46331. }
  46332. if (this.diffuseTexture === texture) {
  46333. return true;
  46334. }
  46335. if (this.specularGlossinessTexture === texture) {
  46336. return true;
  46337. }
  46338. return false;
  46339. };
  46340. /**
  46341. * Makes a duplicate of the current material.
  46342. * @param name - name to use for the new material.
  46343. */
  46344. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46345. var _this = this;
  46346. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46347. clone.id = name;
  46348. clone.name = name;
  46349. return clone;
  46350. };
  46351. /**
  46352. * Serialize the material to a parsable JSON object.
  46353. */
  46354. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46355. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46356. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46357. return serializationObject;
  46358. };
  46359. /**
  46360. * Parses a JSON object correponding to the serialize function.
  46361. */
  46362. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46363. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46364. };
  46365. __decorate([
  46366. BABYLON.serializeAsColor3("diffuse"),
  46367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46368. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46369. __decorate([
  46370. BABYLON.serializeAsTexture(),
  46371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46372. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46373. __decorate([
  46374. BABYLON.serializeAsColor3("specular"),
  46375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46376. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46377. __decorate([
  46378. BABYLON.serialize(),
  46379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46380. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46381. __decorate([
  46382. BABYLON.serializeAsTexture(),
  46383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46384. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46385. return PBRSpecularGlossinessMaterial;
  46386. }(BABYLON.PBRBaseSimpleMaterial));
  46387. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46388. })(BABYLON || (BABYLON = {}));
  46389. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46390. "use strict";
  46391. var BABYLON;
  46392. (function (BABYLON) {
  46393. BABYLON.CameraInputTypes = {};
  46394. var CameraInputsManager = /** @class */ (function () {
  46395. function CameraInputsManager(camera) {
  46396. this.attached = {};
  46397. this.camera = camera;
  46398. this.checkInputs = function () { };
  46399. }
  46400. /**
  46401. * Add an input method to a camera.
  46402. * builtin inputs example: camera.inputs.addGamepad();
  46403. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46404. * @param input camera input method
  46405. */
  46406. CameraInputsManager.prototype.add = function (input) {
  46407. var type = input.getSimpleName();
  46408. if (this.attached[type]) {
  46409. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46410. return;
  46411. }
  46412. this.attached[type] = input;
  46413. input.camera = this.camera;
  46414. //for checkInputs, we are dynamically creating a function
  46415. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46416. if (input.checkInputs) {
  46417. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46418. }
  46419. if (this.attachedElement) {
  46420. input.attachControl(this.attachedElement);
  46421. }
  46422. };
  46423. /**
  46424. * Remove a specific input method from a camera
  46425. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46426. * @param inputToRemove camera input method
  46427. */
  46428. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46429. for (var cam in this.attached) {
  46430. var input = this.attached[cam];
  46431. if (input === inputToRemove) {
  46432. input.detachControl(this.attachedElement);
  46433. input.camera = null;
  46434. delete this.attached[cam];
  46435. this.rebuildInputCheck();
  46436. }
  46437. }
  46438. };
  46439. CameraInputsManager.prototype.removeByType = function (inputType) {
  46440. for (var cam in this.attached) {
  46441. var input = this.attached[cam];
  46442. if (input.getClassName() === inputType) {
  46443. input.detachControl(this.attachedElement);
  46444. input.camera = null;
  46445. delete this.attached[cam];
  46446. this.rebuildInputCheck();
  46447. }
  46448. }
  46449. };
  46450. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46451. var current = this.checkInputs;
  46452. return function () {
  46453. current();
  46454. fn();
  46455. };
  46456. };
  46457. CameraInputsManager.prototype.attachInput = function (input) {
  46458. if (this.attachedElement) {
  46459. input.attachControl(this.attachedElement, this.noPreventDefault);
  46460. }
  46461. };
  46462. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46463. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46464. if (this.attachedElement) {
  46465. return;
  46466. }
  46467. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46468. this.attachedElement = element;
  46469. this.noPreventDefault = noPreventDefault;
  46470. for (var cam in this.attached) {
  46471. this.attached[cam].attachControl(element, noPreventDefault);
  46472. }
  46473. };
  46474. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46475. if (disconnect === void 0) { disconnect = false; }
  46476. if (this.attachedElement !== element) {
  46477. return;
  46478. }
  46479. for (var cam in this.attached) {
  46480. this.attached[cam].detachControl(element);
  46481. if (disconnect) {
  46482. this.attached[cam].camera = null;
  46483. }
  46484. }
  46485. this.attachedElement = null;
  46486. };
  46487. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46488. this.checkInputs = function () { };
  46489. for (var cam in this.attached) {
  46490. var input = this.attached[cam];
  46491. if (input.checkInputs) {
  46492. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46493. }
  46494. }
  46495. };
  46496. /**
  46497. * Remove all attached input methods from a camera
  46498. */
  46499. CameraInputsManager.prototype.clear = function () {
  46500. if (this.attachedElement) {
  46501. this.detachElement(this.attachedElement, true);
  46502. }
  46503. this.attached = {};
  46504. this.attachedElement = null;
  46505. this.checkInputs = function () { };
  46506. };
  46507. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46508. var inputs = {};
  46509. for (var cam in this.attached) {
  46510. var input = this.attached[cam];
  46511. var res = BABYLON.SerializationHelper.Serialize(input);
  46512. inputs[input.getClassName()] = res;
  46513. }
  46514. serializedCamera.inputsmgr = inputs;
  46515. };
  46516. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46517. var parsedInputs = parsedCamera.inputsmgr;
  46518. if (parsedInputs) {
  46519. this.clear();
  46520. for (var n in parsedInputs) {
  46521. var construct = BABYLON.CameraInputTypes[n];
  46522. if (construct) {
  46523. var parsedinput = parsedInputs[n];
  46524. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46525. this.add(input);
  46526. }
  46527. }
  46528. }
  46529. else {
  46530. //2016-03-08 this part is for managing backward compatibility
  46531. for (var n in this.attached) {
  46532. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46533. if (construct) {
  46534. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46535. this.remove(this.attached[n]);
  46536. this.add(input);
  46537. }
  46538. }
  46539. }
  46540. };
  46541. return CameraInputsManager;
  46542. }());
  46543. BABYLON.CameraInputsManager = CameraInputsManager;
  46544. })(BABYLON || (BABYLON = {}));
  46545. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46546. "use strict";
  46547. var BABYLON;
  46548. (function (BABYLON) {
  46549. var TargetCamera = /** @class */ (function (_super) {
  46550. __extends(TargetCamera, _super);
  46551. function TargetCamera(name, position, scene) {
  46552. var _this = _super.call(this, name, position, scene) || this;
  46553. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46554. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46555. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46556. _this.speed = 2.0;
  46557. _this.noRotationConstraint = false;
  46558. _this.lockedTarget = null;
  46559. _this._currentTarget = BABYLON.Vector3.Zero();
  46560. _this._viewMatrix = BABYLON.Matrix.Zero();
  46561. _this._camMatrix = BABYLON.Matrix.Zero();
  46562. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46563. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46564. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46565. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46566. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46567. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46568. _this._tempMatrix = BABYLON.Matrix.Zero();
  46569. return _this;
  46570. }
  46571. TargetCamera.prototype.getFrontPosition = function (distance) {
  46572. this.getWorldMatrix();
  46573. var direction = this.getTarget().subtract(this.position);
  46574. direction.normalize();
  46575. direction.scaleInPlace(distance);
  46576. return this.globalPosition.add(direction);
  46577. };
  46578. TargetCamera.prototype._getLockedTargetPosition = function () {
  46579. if (!this.lockedTarget) {
  46580. return null;
  46581. }
  46582. if (this.lockedTarget.absolutePosition) {
  46583. this.lockedTarget.computeWorldMatrix();
  46584. }
  46585. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46586. };
  46587. TargetCamera.prototype.storeState = function () {
  46588. this._storedPosition = this.position.clone();
  46589. this._storedRotation = this.rotation.clone();
  46590. if (this.rotationQuaternion) {
  46591. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46592. }
  46593. return _super.prototype.storeState.call(this);
  46594. };
  46595. /**
  46596. * Restored camera state. You must call storeState() first
  46597. */
  46598. TargetCamera.prototype._restoreStateValues = function () {
  46599. if (!_super.prototype._restoreStateValues.call(this)) {
  46600. return false;
  46601. }
  46602. this.position = this._storedPosition.clone();
  46603. this.rotation = this._storedRotation.clone();
  46604. if (this.rotationQuaternion) {
  46605. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46606. }
  46607. this.cameraDirection.copyFromFloats(0, 0, 0);
  46608. this.cameraRotation.copyFromFloats(0, 0);
  46609. return true;
  46610. };
  46611. // Cache
  46612. TargetCamera.prototype._initCache = function () {
  46613. _super.prototype._initCache.call(this);
  46614. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46615. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46616. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46617. };
  46618. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46619. if (!ignoreParentClass) {
  46620. _super.prototype._updateCache.call(this);
  46621. }
  46622. var lockedTargetPosition = this._getLockedTargetPosition();
  46623. if (!lockedTargetPosition) {
  46624. this._cache.lockedTarget = null;
  46625. }
  46626. else {
  46627. if (!this._cache.lockedTarget) {
  46628. this._cache.lockedTarget = lockedTargetPosition.clone();
  46629. }
  46630. else {
  46631. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46632. }
  46633. }
  46634. this._cache.rotation.copyFrom(this.rotation);
  46635. if (this.rotationQuaternion)
  46636. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46637. };
  46638. // Synchronized
  46639. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46640. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46641. return false;
  46642. }
  46643. var lockedTargetPosition = this._getLockedTargetPosition();
  46644. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46645. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46646. };
  46647. // Methods
  46648. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46649. var engine = this.getEngine();
  46650. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46651. };
  46652. // Target
  46653. TargetCamera.prototype.setTarget = function (target) {
  46654. this.upVector.normalize();
  46655. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46656. this._camMatrix.invert();
  46657. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46658. var vDir = target.subtract(this.position);
  46659. if (vDir.x >= 0.0) {
  46660. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46661. }
  46662. else {
  46663. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46664. }
  46665. this.rotation.z = 0;
  46666. if (isNaN(this.rotation.x)) {
  46667. this.rotation.x = 0;
  46668. }
  46669. if (isNaN(this.rotation.y)) {
  46670. this.rotation.y = 0;
  46671. }
  46672. if (isNaN(this.rotation.z)) {
  46673. this.rotation.z = 0;
  46674. }
  46675. if (this.rotationQuaternion) {
  46676. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46677. }
  46678. };
  46679. /**
  46680. * Return the current target position of the camera. This value is expressed in local space.
  46681. */
  46682. TargetCamera.prototype.getTarget = function () {
  46683. return this._currentTarget;
  46684. };
  46685. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46686. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46687. };
  46688. TargetCamera.prototype._updatePosition = function () {
  46689. if (this.parent) {
  46690. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46691. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46692. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46693. return;
  46694. }
  46695. this.position.addInPlace(this.cameraDirection);
  46696. };
  46697. TargetCamera.prototype._checkInputs = function () {
  46698. var needToMove = this._decideIfNeedsToMove();
  46699. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46700. // Move
  46701. if (needToMove) {
  46702. this._updatePosition();
  46703. }
  46704. // Rotate
  46705. if (needToRotate) {
  46706. this.rotation.x += this.cameraRotation.x;
  46707. this.rotation.y += this.cameraRotation.y;
  46708. //rotate, if quaternion is set and rotation was used
  46709. if (this.rotationQuaternion) {
  46710. var len = this.rotation.lengthSquared();
  46711. if (len) {
  46712. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46713. }
  46714. }
  46715. if (!this.noRotationConstraint) {
  46716. var limit = (Math.PI / 2) * 0.95;
  46717. if (this.rotation.x > limit)
  46718. this.rotation.x = limit;
  46719. if (this.rotation.x < -limit)
  46720. this.rotation.x = -limit;
  46721. }
  46722. }
  46723. // Inertia
  46724. if (needToMove) {
  46725. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46726. this.cameraDirection.x = 0;
  46727. }
  46728. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46729. this.cameraDirection.y = 0;
  46730. }
  46731. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46732. this.cameraDirection.z = 0;
  46733. }
  46734. this.cameraDirection.scaleInPlace(this.inertia);
  46735. }
  46736. if (needToRotate) {
  46737. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46738. this.cameraRotation.x = 0;
  46739. }
  46740. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46741. this.cameraRotation.y = 0;
  46742. }
  46743. this.cameraRotation.scaleInPlace(this.inertia);
  46744. }
  46745. _super.prototype._checkInputs.call(this);
  46746. };
  46747. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46748. if (this.rotationQuaternion) {
  46749. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46750. }
  46751. else {
  46752. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46753. }
  46754. //update the up vector!
  46755. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46756. };
  46757. TargetCamera.prototype._getViewMatrix = function () {
  46758. if (this.lockedTarget) {
  46759. this.setTarget(this._getLockedTargetPosition());
  46760. }
  46761. // Compute
  46762. this._updateCameraRotationMatrix();
  46763. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46764. // Computing target and final matrix
  46765. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46766. if (this.getScene().useRightHandedSystem) {
  46767. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46768. }
  46769. else {
  46770. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46771. }
  46772. return this._viewMatrix;
  46773. };
  46774. /**
  46775. * @override
  46776. * Override Camera.createRigCamera
  46777. */
  46778. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46779. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46780. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46781. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46782. if (!this.rotationQuaternion) {
  46783. this.rotationQuaternion = new BABYLON.Quaternion();
  46784. }
  46785. rigCamera._cameraRigParams = {};
  46786. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46787. }
  46788. return rigCamera;
  46789. }
  46790. return null;
  46791. };
  46792. /**
  46793. * @override
  46794. * Override Camera._updateRigCameras
  46795. */
  46796. TargetCamera.prototype._updateRigCameras = function () {
  46797. var camLeft = this._rigCameras[0];
  46798. var camRight = this._rigCameras[1];
  46799. switch (this.cameraRigMode) {
  46800. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46801. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46802. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46803. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46804. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46805. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46806. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46807. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46808. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46809. camLeft.setTarget(this.getTarget());
  46810. camRight.setTarget(this.getTarget());
  46811. break;
  46812. case BABYLON.Camera.RIG_MODE_VR:
  46813. if (camLeft.rotationQuaternion) {
  46814. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46815. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46816. }
  46817. else {
  46818. camLeft.rotation.copyFrom(this.rotation);
  46819. camRight.rotation.copyFrom(this.rotation);
  46820. }
  46821. camLeft.position.copyFrom(this.position);
  46822. camRight.position.copyFrom(this.position);
  46823. break;
  46824. }
  46825. _super.prototype._updateRigCameras.call(this);
  46826. };
  46827. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46828. if (!this._rigCamTransformMatrix) {
  46829. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46830. }
  46831. var target = this.getTarget();
  46832. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46833. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46834. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46835. };
  46836. TargetCamera.prototype.getClassName = function () {
  46837. return "TargetCamera";
  46838. };
  46839. __decorate([
  46840. BABYLON.serializeAsVector3()
  46841. ], TargetCamera.prototype, "rotation", void 0);
  46842. __decorate([
  46843. BABYLON.serialize()
  46844. ], TargetCamera.prototype, "speed", void 0);
  46845. __decorate([
  46846. BABYLON.serializeAsMeshReference("lockedTargetId")
  46847. ], TargetCamera.prototype, "lockedTarget", void 0);
  46848. return TargetCamera;
  46849. }(BABYLON.Camera));
  46850. BABYLON.TargetCamera = TargetCamera;
  46851. })(BABYLON || (BABYLON = {}));
  46852. //# sourceMappingURL=babylon.targetCamera.js.map
  46853. "use strict";
  46854. var BABYLON;
  46855. (function (BABYLON) {
  46856. var FreeCameraMouseInput = /** @class */ (function () {
  46857. function FreeCameraMouseInput(touchEnabled) {
  46858. if (touchEnabled === void 0) { touchEnabled = true; }
  46859. this.touchEnabled = touchEnabled;
  46860. this.buttons = [0, 1, 2];
  46861. this.angularSensibility = 2000.0;
  46862. this.previousPosition = null;
  46863. }
  46864. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46865. var _this = this;
  46866. var engine = this.camera.getEngine();
  46867. if (!this._pointerInput) {
  46868. this._pointerInput = function (p, s) {
  46869. var evt = p.event;
  46870. if (engine.isInVRExclusivePointerMode) {
  46871. return;
  46872. }
  46873. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46874. return;
  46875. }
  46876. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46877. return;
  46878. }
  46879. var srcElement = (evt.srcElement || evt.target);
  46880. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46881. try {
  46882. srcElement.setPointerCapture(evt.pointerId);
  46883. }
  46884. catch (e) {
  46885. //Nothing to do with the error. Execution will continue.
  46886. }
  46887. _this.previousPosition = {
  46888. x: evt.clientX,
  46889. y: evt.clientY
  46890. };
  46891. if (!noPreventDefault) {
  46892. evt.preventDefault();
  46893. element.focus();
  46894. }
  46895. }
  46896. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46897. try {
  46898. srcElement.releasePointerCapture(evt.pointerId);
  46899. }
  46900. catch (e) {
  46901. //Nothing to do with the error.
  46902. }
  46903. _this.previousPosition = null;
  46904. if (!noPreventDefault) {
  46905. evt.preventDefault();
  46906. }
  46907. }
  46908. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46909. if (!_this.previousPosition || engine.isPointerLock) {
  46910. return;
  46911. }
  46912. var offsetX = evt.clientX - _this.previousPosition.x;
  46913. var offsetY = evt.clientY - _this.previousPosition.y;
  46914. if (_this.camera.getScene().useRightHandedSystem) {
  46915. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46916. }
  46917. else {
  46918. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46919. }
  46920. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46921. _this.previousPosition = {
  46922. x: evt.clientX,
  46923. y: evt.clientY
  46924. };
  46925. if (!noPreventDefault) {
  46926. evt.preventDefault();
  46927. }
  46928. }
  46929. };
  46930. }
  46931. this._onMouseMove = function (evt) {
  46932. if (!engine.isPointerLock) {
  46933. return;
  46934. }
  46935. if (engine.isInVRExclusivePointerMode) {
  46936. return;
  46937. }
  46938. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46939. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46940. if (_this.camera.getScene().useRightHandedSystem) {
  46941. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46942. }
  46943. else {
  46944. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46945. }
  46946. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46947. _this.previousPosition = null;
  46948. if (!noPreventDefault) {
  46949. evt.preventDefault();
  46950. }
  46951. };
  46952. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46953. element.addEventListener("mousemove", this._onMouseMove, false);
  46954. };
  46955. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46956. if (this._observer && element) {
  46957. this.camera.getScene().onPointerObservable.remove(this._observer);
  46958. if (this._onMouseMove) {
  46959. element.removeEventListener("mousemove", this._onMouseMove);
  46960. }
  46961. this._observer = null;
  46962. this._onMouseMove = null;
  46963. this.previousPosition = null;
  46964. }
  46965. };
  46966. FreeCameraMouseInput.prototype.getClassName = function () {
  46967. return "FreeCameraMouseInput";
  46968. };
  46969. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46970. return "mouse";
  46971. };
  46972. __decorate([
  46973. BABYLON.serialize()
  46974. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46975. __decorate([
  46976. BABYLON.serialize()
  46977. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46978. return FreeCameraMouseInput;
  46979. }());
  46980. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46981. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46982. })(BABYLON || (BABYLON = {}));
  46983. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46984. "use strict";
  46985. var BABYLON;
  46986. (function (BABYLON) {
  46987. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46988. function FreeCameraKeyboardMoveInput() {
  46989. this._keys = new Array();
  46990. this.keysUp = [38];
  46991. this.keysDown = [40];
  46992. this.keysLeft = [37];
  46993. this.keysRight = [39];
  46994. }
  46995. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46996. var _this = this;
  46997. if (this._onCanvasBlurObserver) {
  46998. return;
  46999. }
  47000. this._scene = this.camera.getScene();
  47001. this._engine = this._scene.getEngine();
  47002. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47003. _this._keys = [];
  47004. });
  47005. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47006. var evt = info.event;
  47007. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47008. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47009. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47010. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47011. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47012. var index = _this._keys.indexOf(evt.keyCode);
  47013. if (index === -1) {
  47014. _this._keys.push(evt.keyCode);
  47015. }
  47016. if (!noPreventDefault) {
  47017. evt.preventDefault();
  47018. }
  47019. }
  47020. }
  47021. else {
  47022. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47023. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47024. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47025. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47026. var index = _this._keys.indexOf(evt.keyCode);
  47027. if (index >= 0) {
  47028. _this._keys.splice(index, 1);
  47029. }
  47030. if (!noPreventDefault) {
  47031. evt.preventDefault();
  47032. }
  47033. }
  47034. }
  47035. });
  47036. };
  47037. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47038. if (this._scene) {
  47039. if (this._onKeyboardObserver) {
  47040. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47041. }
  47042. if (this._onCanvasBlurObserver) {
  47043. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47044. }
  47045. this._onKeyboardObserver = null;
  47046. this._onCanvasBlurObserver = null;
  47047. }
  47048. this._keys = [];
  47049. };
  47050. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47051. if (this._onKeyboardObserver) {
  47052. var camera = this.camera;
  47053. // Keyboard
  47054. for (var index = 0; index < this._keys.length; index++) {
  47055. var keyCode = this._keys[index];
  47056. var speed = camera._computeLocalCameraSpeed();
  47057. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47058. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47059. }
  47060. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47061. camera._localDirection.copyFromFloats(0, 0, speed);
  47062. }
  47063. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47064. camera._localDirection.copyFromFloats(speed, 0, 0);
  47065. }
  47066. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47067. camera._localDirection.copyFromFloats(0, 0, -speed);
  47068. }
  47069. if (camera.getScene().useRightHandedSystem) {
  47070. camera._localDirection.z *= -1;
  47071. }
  47072. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47073. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47074. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47075. }
  47076. }
  47077. };
  47078. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47079. return "FreeCameraKeyboardMoveInput";
  47080. };
  47081. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47082. this._keys = [];
  47083. };
  47084. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47085. return "keyboard";
  47086. };
  47087. __decorate([
  47088. BABYLON.serialize()
  47089. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47090. __decorate([
  47091. BABYLON.serialize()
  47092. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47093. __decorate([
  47094. BABYLON.serialize()
  47095. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47096. __decorate([
  47097. BABYLON.serialize()
  47098. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47099. return FreeCameraKeyboardMoveInput;
  47100. }());
  47101. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47102. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47103. })(BABYLON || (BABYLON = {}));
  47104. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47105. "use strict";
  47106. var BABYLON;
  47107. (function (BABYLON) {
  47108. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47109. __extends(FreeCameraInputsManager, _super);
  47110. function FreeCameraInputsManager(camera) {
  47111. return _super.call(this, camera) || this;
  47112. }
  47113. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47114. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47115. return this;
  47116. };
  47117. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47118. if (touchEnabled === void 0) { touchEnabled = true; }
  47119. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47120. return this;
  47121. };
  47122. FreeCameraInputsManager.prototype.addGamepad = function () {
  47123. this.add(new BABYLON.FreeCameraGamepadInput());
  47124. return this;
  47125. };
  47126. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47127. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47128. return this;
  47129. };
  47130. FreeCameraInputsManager.prototype.addTouch = function () {
  47131. this.add(new BABYLON.FreeCameraTouchInput());
  47132. return this;
  47133. };
  47134. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47135. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47136. return this;
  47137. };
  47138. return FreeCameraInputsManager;
  47139. }(BABYLON.CameraInputsManager));
  47140. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47141. })(BABYLON || (BABYLON = {}));
  47142. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47143. "use strict";
  47144. var BABYLON;
  47145. (function (BABYLON) {
  47146. var FreeCamera = /** @class */ (function (_super) {
  47147. __extends(FreeCamera, _super);
  47148. function FreeCamera(name, position, scene) {
  47149. var _this = _super.call(this, name, position, scene) || this;
  47150. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47151. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47152. _this.checkCollisions = false;
  47153. _this.applyGravity = false;
  47154. _this._needMoveForGravity = false;
  47155. _this._oldPosition = BABYLON.Vector3.Zero();
  47156. _this._diffPosition = BABYLON.Vector3.Zero();
  47157. _this._newPosition = BABYLON.Vector3.Zero();
  47158. // Collisions
  47159. _this._collisionMask = -1;
  47160. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47161. if (collidedMesh === void 0) { collidedMesh = null; }
  47162. //TODO move this to the collision coordinator!
  47163. if (_this.getScene().workerCollisions)
  47164. newPosition.multiplyInPlace(_this._collider._radius);
  47165. var updatePosition = function (newPos) {
  47166. _this._newPosition.copyFrom(newPos);
  47167. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47168. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47169. _this.position.addInPlace(_this._diffPosition);
  47170. if (_this.onCollide && collidedMesh) {
  47171. _this.onCollide(collidedMesh);
  47172. }
  47173. }
  47174. };
  47175. updatePosition(newPosition);
  47176. };
  47177. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47178. _this.inputs.addKeyboard().addMouse();
  47179. return _this;
  47180. }
  47181. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47182. //-- begin properties for backward compatibility for inputs
  47183. /**
  47184. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47185. * Higher values reduce sensitivity.
  47186. */
  47187. get: function () {
  47188. var mouse = this.inputs.attached["mouse"];
  47189. if (mouse)
  47190. return mouse.angularSensibility;
  47191. return 0;
  47192. },
  47193. /**
  47194. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47195. * Higher values reduce sensitivity.
  47196. */
  47197. set: function (value) {
  47198. var mouse = this.inputs.attached["mouse"];
  47199. if (mouse)
  47200. mouse.angularSensibility = value;
  47201. },
  47202. enumerable: true,
  47203. configurable: true
  47204. });
  47205. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47206. get: function () {
  47207. var keyboard = this.inputs.attached["keyboard"];
  47208. if (keyboard)
  47209. return keyboard.keysUp;
  47210. return [];
  47211. },
  47212. set: function (value) {
  47213. var keyboard = this.inputs.attached["keyboard"];
  47214. if (keyboard)
  47215. keyboard.keysUp = value;
  47216. },
  47217. enumerable: true,
  47218. configurable: true
  47219. });
  47220. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47221. get: function () {
  47222. var keyboard = this.inputs.attached["keyboard"];
  47223. if (keyboard)
  47224. return keyboard.keysDown;
  47225. return [];
  47226. },
  47227. set: function (value) {
  47228. var keyboard = this.inputs.attached["keyboard"];
  47229. if (keyboard)
  47230. keyboard.keysDown = value;
  47231. },
  47232. enumerable: true,
  47233. configurable: true
  47234. });
  47235. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47236. get: function () {
  47237. var keyboard = this.inputs.attached["keyboard"];
  47238. if (keyboard)
  47239. return keyboard.keysLeft;
  47240. return [];
  47241. },
  47242. set: function (value) {
  47243. var keyboard = this.inputs.attached["keyboard"];
  47244. if (keyboard)
  47245. keyboard.keysLeft = value;
  47246. },
  47247. enumerable: true,
  47248. configurable: true
  47249. });
  47250. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47251. get: function () {
  47252. var keyboard = this.inputs.attached["keyboard"];
  47253. if (keyboard)
  47254. return keyboard.keysRight;
  47255. return [];
  47256. },
  47257. set: function (value) {
  47258. var keyboard = this.inputs.attached["keyboard"];
  47259. if (keyboard)
  47260. keyboard.keysRight = value;
  47261. },
  47262. enumerable: true,
  47263. configurable: true
  47264. });
  47265. // Controls
  47266. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47267. this.inputs.attachElement(element, noPreventDefault);
  47268. };
  47269. FreeCamera.prototype.detachControl = function (element) {
  47270. this.inputs.detachElement(element);
  47271. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47272. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47273. };
  47274. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47275. get: function () {
  47276. return this._collisionMask;
  47277. },
  47278. set: function (mask) {
  47279. this._collisionMask = !isNaN(mask) ? mask : -1;
  47280. },
  47281. enumerable: true,
  47282. configurable: true
  47283. });
  47284. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47285. var globalPosition;
  47286. if (this.parent) {
  47287. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47288. }
  47289. else {
  47290. globalPosition = this.position;
  47291. }
  47292. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47293. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47294. if (!this._collider) {
  47295. this._collider = new BABYLON.Collider();
  47296. }
  47297. this._collider._radius = this.ellipsoid;
  47298. this._collider.collisionMask = this._collisionMask;
  47299. //no need for clone, as long as gravity is not on.
  47300. var actualDisplacement = displacement;
  47301. //add gravity to the direction to prevent the dual-collision checking
  47302. if (this.applyGravity) {
  47303. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47304. actualDisplacement = displacement.add(this.getScene().gravity);
  47305. }
  47306. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47307. };
  47308. FreeCamera.prototype._checkInputs = function () {
  47309. if (!this._localDirection) {
  47310. this._localDirection = BABYLON.Vector3.Zero();
  47311. this._transformedDirection = BABYLON.Vector3.Zero();
  47312. }
  47313. this.inputs.checkInputs();
  47314. _super.prototype._checkInputs.call(this);
  47315. };
  47316. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47317. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47318. };
  47319. FreeCamera.prototype._updatePosition = function () {
  47320. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47321. this._collideWithWorld(this.cameraDirection);
  47322. }
  47323. else {
  47324. _super.prototype._updatePosition.call(this);
  47325. }
  47326. };
  47327. FreeCamera.prototype.dispose = function () {
  47328. this.inputs.clear();
  47329. _super.prototype.dispose.call(this);
  47330. };
  47331. FreeCamera.prototype.getClassName = function () {
  47332. return "FreeCamera";
  47333. };
  47334. __decorate([
  47335. BABYLON.serializeAsVector3()
  47336. ], FreeCamera.prototype, "ellipsoid", void 0);
  47337. __decorate([
  47338. BABYLON.serializeAsVector3()
  47339. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47340. __decorate([
  47341. BABYLON.serialize()
  47342. ], FreeCamera.prototype, "checkCollisions", void 0);
  47343. __decorate([
  47344. BABYLON.serialize()
  47345. ], FreeCamera.prototype, "applyGravity", void 0);
  47346. return FreeCamera;
  47347. }(BABYLON.TargetCamera));
  47348. BABYLON.FreeCamera = FreeCamera;
  47349. })(BABYLON || (BABYLON = {}));
  47350. //# sourceMappingURL=babylon.freeCamera.js.map
  47351. "use strict";
  47352. var BABYLON;
  47353. (function (BABYLON) {
  47354. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47355. function ArcRotateCameraKeyboardMoveInput() {
  47356. this._keys = new Array();
  47357. this.keysUp = [38];
  47358. this.keysDown = [40];
  47359. this.keysLeft = [37];
  47360. this.keysRight = [39];
  47361. this.keysReset = [220];
  47362. this.panningSensibility = 50.0;
  47363. this.zoomingSensibility = 25.0;
  47364. this.useAltToZoom = true;
  47365. }
  47366. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47367. var _this = this;
  47368. if (this._onCanvasBlurObserver) {
  47369. return;
  47370. }
  47371. this._scene = this.camera.getScene();
  47372. this._engine = this._scene.getEngine();
  47373. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47374. _this._keys = [];
  47375. });
  47376. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47377. var evt = info.event;
  47378. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47379. _this._ctrlPressed = evt.ctrlKey;
  47380. _this._altPressed = evt.altKey;
  47381. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47382. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47383. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47384. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47385. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47386. var index = _this._keys.indexOf(evt.keyCode);
  47387. if (index === -1) {
  47388. _this._keys.push(evt.keyCode);
  47389. }
  47390. if (evt.preventDefault) {
  47391. if (!noPreventDefault) {
  47392. evt.preventDefault();
  47393. }
  47394. }
  47395. }
  47396. }
  47397. else {
  47398. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47399. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47400. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47401. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47402. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47403. var index = _this._keys.indexOf(evt.keyCode);
  47404. if (index >= 0) {
  47405. _this._keys.splice(index, 1);
  47406. }
  47407. if (evt.preventDefault) {
  47408. if (!noPreventDefault) {
  47409. evt.preventDefault();
  47410. }
  47411. }
  47412. }
  47413. }
  47414. });
  47415. };
  47416. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47417. if (this._scene) {
  47418. if (this._onKeyboardObserver) {
  47419. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47420. }
  47421. if (this._onCanvasBlurObserver) {
  47422. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47423. }
  47424. this._onKeyboardObserver = null;
  47425. this._onCanvasBlurObserver = null;
  47426. }
  47427. this._keys = [];
  47428. };
  47429. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47430. if (this._onKeyboardObserver) {
  47431. var camera = this.camera;
  47432. for (var index = 0; index < this._keys.length; index++) {
  47433. var keyCode = this._keys[index];
  47434. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47435. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47436. camera.inertialPanningX -= 1 / this.panningSensibility;
  47437. }
  47438. else {
  47439. camera.inertialAlphaOffset -= 0.01;
  47440. }
  47441. }
  47442. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47443. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47444. camera.inertialPanningY += 1 / this.panningSensibility;
  47445. }
  47446. else if (this._altPressed && this.useAltToZoom) {
  47447. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47448. }
  47449. else {
  47450. camera.inertialBetaOffset -= 0.01;
  47451. }
  47452. }
  47453. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47454. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47455. camera.inertialPanningX += 1 / this.panningSensibility;
  47456. }
  47457. else {
  47458. camera.inertialAlphaOffset += 0.01;
  47459. }
  47460. }
  47461. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47462. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47463. camera.inertialPanningY -= 1 / this.panningSensibility;
  47464. }
  47465. else if (this._altPressed && this.useAltToZoom) {
  47466. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47467. }
  47468. else {
  47469. camera.inertialBetaOffset += 0.01;
  47470. }
  47471. }
  47472. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47473. camera.restoreState();
  47474. }
  47475. }
  47476. }
  47477. };
  47478. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47479. return "ArcRotateCameraKeyboardMoveInput";
  47480. };
  47481. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47482. return "keyboard";
  47483. };
  47484. __decorate([
  47485. BABYLON.serialize()
  47486. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47487. __decorate([
  47488. BABYLON.serialize()
  47489. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47490. __decorate([
  47491. BABYLON.serialize()
  47492. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47493. __decorate([
  47494. BABYLON.serialize()
  47495. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47496. __decorate([
  47497. BABYLON.serialize()
  47498. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47499. __decorate([
  47500. BABYLON.serialize()
  47501. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47502. __decorate([
  47503. BABYLON.serialize()
  47504. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47505. __decorate([
  47506. BABYLON.serialize()
  47507. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47508. return ArcRotateCameraKeyboardMoveInput;
  47509. }());
  47510. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47511. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47512. })(BABYLON || (BABYLON = {}));
  47513. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47514. "use strict";
  47515. var BABYLON;
  47516. (function (BABYLON) {
  47517. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47518. function ArcRotateCameraMouseWheelInput() {
  47519. this.wheelPrecision = 3.0;
  47520. /**
  47521. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47522. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47523. */
  47524. this.wheelDeltaPercentage = 0;
  47525. }
  47526. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47527. var _this = this;
  47528. this._wheel = function (p, s) {
  47529. //sanity check - this should be a PointerWheel event.
  47530. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47531. return;
  47532. var event = p.event;
  47533. var delta = 0;
  47534. if (event.wheelDelta) {
  47535. if (_this.wheelDeltaPercentage) {
  47536. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47537. if (event.wheelDelta > 0) {
  47538. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47539. }
  47540. else {
  47541. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47542. }
  47543. }
  47544. else {
  47545. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47546. }
  47547. }
  47548. else if (event.detail) {
  47549. delta = -event.detail / _this.wheelPrecision;
  47550. }
  47551. if (delta)
  47552. _this.camera.inertialRadiusOffset += delta;
  47553. if (event.preventDefault) {
  47554. if (!noPreventDefault) {
  47555. event.preventDefault();
  47556. }
  47557. }
  47558. };
  47559. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47560. };
  47561. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47562. if (this._observer && element) {
  47563. this.camera.getScene().onPointerObservable.remove(this._observer);
  47564. this._observer = null;
  47565. this._wheel = null;
  47566. }
  47567. };
  47568. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47569. return "ArcRotateCameraMouseWheelInput";
  47570. };
  47571. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47572. return "mousewheel";
  47573. };
  47574. __decorate([
  47575. BABYLON.serialize()
  47576. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47577. __decorate([
  47578. BABYLON.serialize()
  47579. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47580. return ArcRotateCameraMouseWheelInput;
  47581. }());
  47582. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47583. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47584. })(BABYLON || (BABYLON = {}));
  47585. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47586. "use strict";
  47587. var BABYLON;
  47588. (function (BABYLON) {
  47589. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47590. function ArcRotateCameraPointersInput() {
  47591. this.buttons = [0, 1, 2];
  47592. this.angularSensibilityX = 1000.0;
  47593. this.angularSensibilityY = 1000.0;
  47594. this.pinchPrecision = 12.0;
  47595. /**
  47596. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47597. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47598. */
  47599. this.pinchDeltaPercentage = 0;
  47600. this.panningSensibility = 1000.0;
  47601. this.multiTouchPanning = true;
  47602. this.multiTouchPanAndZoom = true;
  47603. this._isPanClick = false;
  47604. this.pinchInwards = true;
  47605. }
  47606. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47607. var _this = this;
  47608. var engine = this.camera.getEngine();
  47609. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47610. var pointA = null;
  47611. var pointB = null;
  47612. var previousPinchSquaredDistance = 0;
  47613. var initialDistance = 0;
  47614. var twoFingerActivityCount = 0;
  47615. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47616. this._pointerInput = function (p, s) {
  47617. var evt = p.event;
  47618. var isTouch = p.event.pointerType === "touch";
  47619. if (engine.isInVRExclusivePointerMode) {
  47620. return;
  47621. }
  47622. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47623. return;
  47624. }
  47625. var srcElement = (evt.srcElement || evt.target);
  47626. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47627. try {
  47628. srcElement.setPointerCapture(evt.pointerId);
  47629. }
  47630. catch (e) {
  47631. //Nothing to do with the error. Execution will continue.
  47632. }
  47633. // Manage panning with pan button click
  47634. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47635. // manage pointers
  47636. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47637. if (pointA === null) {
  47638. pointA = cacheSoloPointer;
  47639. }
  47640. else if (pointB === null) {
  47641. pointB = cacheSoloPointer;
  47642. }
  47643. if (!noPreventDefault) {
  47644. evt.preventDefault();
  47645. element.focus();
  47646. }
  47647. }
  47648. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47649. _this.camera.restoreState();
  47650. }
  47651. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47652. try {
  47653. srcElement.releasePointerCapture(evt.pointerId);
  47654. }
  47655. catch (e) {
  47656. //Nothing to do with the error.
  47657. }
  47658. cacheSoloPointer = null;
  47659. previousPinchSquaredDistance = 0;
  47660. previousMultiTouchPanPosition.isPaning = false;
  47661. previousMultiTouchPanPosition.isPinching = false;
  47662. twoFingerActivityCount = 0;
  47663. initialDistance = 0;
  47664. if (!isTouch) {
  47665. pointB = null; // Mouse and pen are mono pointer
  47666. }
  47667. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47668. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47669. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47670. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47671. if (engine._badOS) {
  47672. pointA = pointB = null;
  47673. }
  47674. else {
  47675. //only remove the impacted pointer in case of multitouch allowing on most
  47676. //platforms switching from rotate to zoom and pan seamlessly.
  47677. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47678. pointA = pointB;
  47679. pointB = null;
  47680. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47681. }
  47682. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47683. pointB = null;
  47684. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47685. }
  47686. else {
  47687. pointA = pointB = null;
  47688. }
  47689. }
  47690. if (!noPreventDefault) {
  47691. evt.preventDefault();
  47692. }
  47693. }
  47694. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47695. if (!noPreventDefault) {
  47696. evt.preventDefault();
  47697. }
  47698. // One button down
  47699. if (pointA && pointB === null && cacheSoloPointer) {
  47700. if (_this.panningSensibility !== 0 &&
  47701. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47702. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47703. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47704. }
  47705. else {
  47706. var offsetX = evt.clientX - cacheSoloPointer.x;
  47707. var offsetY = evt.clientY - cacheSoloPointer.y;
  47708. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47709. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47710. }
  47711. cacheSoloPointer.x = evt.clientX;
  47712. cacheSoloPointer.y = evt.clientY;
  47713. }
  47714. else if (pointA && pointB) {
  47715. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47716. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47717. ed.x = evt.clientX;
  47718. ed.y = evt.clientY;
  47719. var direction = _this.pinchInwards ? 1 : -1;
  47720. var distX = pointA.x - pointB.x;
  47721. var distY = pointA.y - pointB.y;
  47722. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47723. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47724. if (previousPinchSquaredDistance === 0) {
  47725. initialDistance = pinchDistance;
  47726. previousPinchSquaredDistance = pinchSquaredDistance;
  47727. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47728. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47729. return;
  47730. }
  47731. if (_this.multiTouchPanAndZoom) {
  47732. if (_this.pinchDeltaPercentage) {
  47733. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47734. }
  47735. else {
  47736. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47737. (_this.pinchPrecision *
  47738. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47739. direction);
  47740. }
  47741. if (_this.panningSensibility !== 0) {
  47742. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47743. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47744. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47745. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47746. previousMultiTouchPanPosition.x = pointersCenterX;
  47747. previousMultiTouchPanPosition.y = pointersCenterY;
  47748. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47749. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47750. }
  47751. }
  47752. else {
  47753. twoFingerActivityCount++;
  47754. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47755. if (_this.pinchDeltaPercentage) {
  47756. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47757. }
  47758. else {
  47759. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47760. (_this.pinchPrecision *
  47761. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47762. direction);
  47763. }
  47764. previousMultiTouchPanPosition.isPaning = false;
  47765. previousMultiTouchPanPosition.isPinching = true;
  47766. }
  47767. else {
  47768. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47769. if (!previousMultiTouchPanPosition.isPaning) {
  47770. previousMultiTouchPanPosition.isPaning = true;
  47771. previousMultiTouchPanPosition.isPinching = false;
  47772. previousMultiTouchPanPosition.x = ed.x;
  47773. previousMultiTouchPanPosition.y = ed.y;
  47774. return;
  47775. }
  47776. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47777. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47778. }
  47779. }
  47780. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47781. previousMultiTouchPanPosition.x = ed.x;
  47782. previousMultiTouchPanPosition.y = ed.y;
  47783. }
  47784. }
  47785. previousPinchSquaredDistance = pinchSquaredDistance;
  47786. }
  47787. }
  47788. };
  47789. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47790. this._onContextMenu = function (evt) {
  47791. evt.preventDefault();
  47792. };
  47793. if (!this.camera._useCtrlForPanning) {
  47794. element.addEventListener("contextmenu", this._onContextMenu, false);
  47795. }
  47796. this._onLostFocus = function () {
  47797. //this._keys = [];
  47798. pointA = pointB = null;
  47799. previousPinchSquaredDistance = 0;
  47800. previousMultiTouchPanPosition.isPaning = false;
  47801. previousMultiTouchPanPosition.isPinching = false;
  47802. twoFingerActivityCount = 0;
  47803. cacheSoloPointer = null;
  47804. initialDistance = 0;
  47805. };
  47806. this._onMouseMove = function (evt) {
  47807. if (!engine.isPointerLock) {
  47808. return;
  47809. }
  47810. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47811. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47812. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47813. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47814. if (!noPreventDefault) {
  47815. evt.preventDefault();
  47816. }
  47817. };
  47818. this._onGestureStart = function (e) {
  47819. if (window.MSGesture === undefined) {
  47820. return;
  47821. }
  47822. if (!_this._MSGestureHandler) {
  47823. _this._MSGestureHandler = new MSGesture();
  47824. _this._MSGestureHandler.target = element;
  47825. }
  47826. _this._MSGestureHandler.addPointer(e.pointerId);
  47827. };
  47828. this._onGesture = function (e) {
  47829. _this.camera.radius *= e.scale;
  47830. if (e.preventDefault) {
  47831. if (!noPreventDefault) {
  47832. e.stopPropagation();
  47833. e.preventDefault();
  47834. }
  47835. }
  47836. };
  47837. element.addEventListener("mousemove", this._onMouseMove, false);
  47838. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47839. element.addEventListener("MSGestureChange", this._onGesture, false);
  47840. BABYLON.Tools.RegisterTopRootEvents([
  47841. { name: "blur", handler: this._onLostFocus }
  47842. ]);
  47843. };
  47844. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47845. if (this._onLostFocus) {
  47846. BABYLON.Tools.UnregisterTopRootEvents([
  47847. { name: "blur", handler: this._onLostFocus }
  47848. ]);
  47849. }
  47850. if (element && this._observer) {
  47851. this.camera.getScene().onPointerObservable.remove(this._observer);
  47852. this._observer = null;
  47853. if (this._onContextMenu) {
  47854. element.removeEventListener("contextmenu", this._onContextMenu);
  47855. }
  47856. if (this._onMouseMove) {
  47857. element.removeEventListener("mousemove", this._onMouseMove);
  47858. }
  47859. if (this._onGestureStart) {
  47860. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47861. }
  47862. if (this._onGesture) {
  47863. element.removeEventListener("MSGestureChange", this._onGesture);
  47864. }
  47865. this._isPanClick = false;
  47866. this.pinchInwards = true;
  47867. this._onMouseMove = null;
  47868. this._onGestureStart = null;
  47869. this._onGesture = null;
  47870. this._MSGestureHandler = null;
  47871. this._onLostFocus = null;
  47872. this._onContextMenu = null;
  47873. }
  47874. };
  47875. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47876. return "ArcRotateCameraPointersInput";
  47877. };
  47878. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47879. return "pointers";
  47880. };
  47881. __decorate([
  47882. BABYLON.serialize()
  47883. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47884. __decorate([
  47885. BABYLON.serialize()
  47886. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47887. __decorate([
  47888. BABYLON.serialize()
  47889. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47890. __decorate([
  47891. BABYLON.serialize()
  47892. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47893. __decorate([
  47894. BABYLON.serialize()
  47895. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47896. __decorate([
  47897. BABYLON.serialize()
  47898. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47899. __decorate([
  47900. BABYLON.serialize()
  47901. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47902. __decorate([
  47903. BABYLON.serialize()
  47904. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47905. return ArcRotateCameraPointersInput;
  47906. }());
  47907. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47908. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47909. })(BABYLON || (BABYLON = {}));
  47910. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47911. "use strict";
  47912. var BABYLON;
  47913. (function (BABYLON) {
  47914. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47915. __extends(ArcRotateCameraInputsManager, _super);
  47916. function ArcRotateCameraInputsManager(camera) {
  47917. return _super.call(this, camera) || this;
  47918. }
  47919. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47920. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47921. return this;
  47922. };
  47923. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47924. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47925. return this;
  47926. };
  47927. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47928. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47929. return this;
  47930. };
  47931. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47932. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47933. return this;
  47934. };
  47935. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47936. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47937. return this;
  47938. };
  47939. return ArcRotateCameraInputsManager;
  47940. }(BABYLON.CameraInputsManager));
  47941. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47942. })(BABYLON || (BABYLON = {}));
  47943. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47944. "use strict";
  47945. var BABYLON;
  47946. (function (BABYLON) {
  47947. var ArcRotateCamera = /** @class */ (function (_super) {
  47948. __extends(ArcRotateCamera, _super);
  47949. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47950. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47951. _this.inertialAlphaOffset = 0;
  47952. _this.inertialBetaOffset = 0;
  47953. _this.inertialRadiusOffset = 0;
  47954. _this.lowerAlphaLimit = null;
  47955. _this.upperAlphaLimit = null;
  47956. _this.lowerBetaLimit = 0.01;
  47957. _this.upperBetaLimit = Math.PI;
  47958. _this.lowerRadiusLimit = null;
  47959. _this.upperRadiusLimit = null;
  47960. _this.inertialPanningX = 0;
  47961. _this.inertialPanningY = 0;
  47962. _this.pinchToPanMaxDistance = 20;
  47963. _this.panningDistanceLimit = null;
  47964. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47965. _this.panningInertia = 0.9;
  47966. //-- end properties for backward compatibility for inputs
  47967. _this.zoomOnFactor = 1;
  47968. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47969. _this.allowUpsideDown = true;
  47970. _this._viewMatrix = new BABYLON.Matrix();
  47971. // Panning
  47972. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47973. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47974. _this.checkCollisions = false;
  47975. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47976. _this._previousPosition = BABYLON.Vector3.Zero();
  47977. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47978. _this._newPosition = BABYLON.Vector3.Zero();
  47979. _this._computationVector = BABYLON.Vector3.Zero();
  47980. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47981. if (collidedMesh === void 0) { collidedMesh = null; }
  47982. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47983. newPosition.multiplyInPlace(_this._collider._radius);
  47984. }
  47985. if (!collidedMesh) {
  47986. _this._previousPosition.copyFrom(_this.position);
  47987. }
  47988. else {
  47989. _this.setPosition(newPosition);
  47990. if (_this.onCollide) {
  47991. _this.onCollide(collidedMesh);
  47992. }
  47993. }
  47994. // Recompute because of constraints
  47995. var cosa = Math.cos(_this.alpha);
  47996. var sina = Math.sin(_this.alpha);
  47997. var cosb = Math.cos(_this.beta);
  47998. var sinb = Math.sin(_this.beta);
  47999. if (sinb === 0) {
  48000. sinb = 0.0001;
  48001. }
  48002. var target = _this._getTargetPosition();
  48003. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48004. target.addToRef(_this._computationVector, _this._newPosition);
  48005. _this.position.copyFrom(_this._newPosition);
  48006. var up = _this.upVector;
  48007. if (_this.allowUpsideDown && _this.beta < 0) {
  48008. up = up.clone();
  48009. up = up.negate();
  48010. }
  48011. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48012. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48013. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48014. _this._collisionTriggered = false;
  48015. };
  48016. _this._target = BABYLON.Vector3.Zero();
  48017. if (target) {
  48018. _this.setTarget(target);
  48019. }
  48020. _this.alpha = alpha;
  48021. _this.beta = beta;
  48022. _this.radius = radius;
  48023. _this.getViewMatrix();
  48024. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48025. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48026. return _this;
  48027. }
  48028. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48029. get: function () {
  48030. return this._target;
  48031. },
  48032. set: function (value) {
  48033. this.setTarget(value);
  48034. },
  48035. enumerable: true,
  48036. configurable: true
  48037. });
  48038. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48039. //-- begin properties for backward compatibility for inputs
  48040. get: function () {
  48041. var pointers = this.inputs.attached["pointers"];
  48042. if (pointers)
  48043. return pointers.angularSensibilityX;
  48044. return 0;
  48045. },
  48046. set: function (value) {
  48047. var pointers = this.inputs.attached["pointers"];
  48048. if (pointers) {
  48049. pointers.angularSensibilityX = value;
  48050. }
  48051. },
  48052. enumerable: true,
  48053. configurable: true
  48054. });
  48055. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48056. get: function () {
  48057. var pointers = this.inputs.attached["pointers"];
  48058. if (pointers)
  48059. return pointers.angularSensibilityY;
  48060. return 0;
  48061. },
  48062. set: function (value) {
  48063. var pointers = this.inputs.attached["pointers"];
  48064. if (pointers) {
  48065. pointers.angularSensibilityY = value;
  48066. }
  48067. },
  48068. enumerable: true,
  48069. configurable: true
  48070. });
  48071. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48072. get: function () {
  48073. var pointers = this.inputs.attached["pointers"];
  48074. if (pointers)
  48075. return pointers.pinchPrecision;
  48076. return 0;
  48077. },
  48078. set: function (value) {
  48079. var pointers = this.inputs.attached["pointers"];
  48080. if (pointers) {
  48081. pointers.pinchPrecision = value;
  48082. }
  48083. },
  48084. enumerable: true,
  48085. configurable: true
  48086. });
  48087. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48088. get: function () {
  48089. var pointers = this.inputs.attached["pointers"];
  48090. if (pointers)
  48091. return pointers.pinchDeltaPercentage;
  48092. return 0;
  48093. },
  48094. set: function (value) {
  48095. var pointers = this.inputs.attached["pointers"];
  48096. if (pointers) {
  48097. pointers.pinchDeltaPercentage = value;
  48098. }
  48099. },
  48100. enumerable: true,
  48101. configurable: true
  48102. });
  48103. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48104. get: function () {
  48105. var pointers = this.inputs.attached["pointers"];
  48106. if (pointers)
  48107. return pointers.panningSensibility;
  48108. return 0;
  48109. },
  48110. set: function (value) {
  48111. var pointers = this.inputs.attached["pointers"];
  48112. if (pointers) {
  48113. pointers.panningSensibility = value;
  48114. }
  48115. },
  48116. enumerable: true,
  48117. configurable: true
  48118. });
  48119. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48120. get: function () {
  48121. var keyboard = this.inputs.attached["keyboard"];
  48122. if (keyboard)
  48123. return keyboard.keysUp;
  48124. return [];
  48125. },
  48126. set: function (value) {
  48127. var keyboard = this.inputs.attached["keyboard"];
  48128. if (keyboard)
  48129. keyboard.keysUp = value;
  48130. },
  48131. enumerable: true,
  48132. configurable: true
  48133. });
  48134. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48135. get: function () {
  48136. var keyboard = this.inputs.attached["keyboard"];
  48137. if (keyboard)
  48138. return keyboard.keysDown;
  48139. return [];
  48140. },
  48141. set: function (value) {
  48142. var keyboard = this.inputs.attached["keyboard"];
  48143. if (keyboard)
  48144. keyboard.keysDown = value;
  48145. },
  48146. enumerable: true,
  48147. configurable: true
  48148. });
  48149. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48150. get: function () {
  48151. var keyboard = this.inputs.attached["keyboard"];
  48152. if (keyboard)
  48153. return keyboard.keysLeft;
  48154. return [];
  48155. },
  48156. set: function (value) {
  48157. var keyboard = this.inputs.attached["keyboard"];
  48158. if (keyboard)
  48159. keyboard.keysLeft = value;
  48160. },
  48161. enumerable: true,
  48162. configurable: true
  48163. });
  48164. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48165. get: function () {
  48166. var keyboard = this.inputs.attached["keyboard"];
  48167. if (keyboard)
  48168. return keyboard.keysRight;
  48169. return [];
  48170. },
  48171. set: function (value) {
  48172. var keyboard = this.inputs.attached["keyboard"];
  48173. if (keyboard)
  48174. keyboard.keysRight = value;
  48175. },
  48176. enumerable: true,
  48177. configurable: true
  48178. });
  48179. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48180. get: function () {
  48181. var mousewheel = this.inputs.attached["mousewheel"];
  48182. if (mousewheel)
  48183. return mousewheel.wheelPrecision;
  48184. return 0;
  48185. },
  48186. set: function (value) {
  48187. var mousewheel = this.inputs.attached["mousewheel"];
  48188. if (mousewheel)
  48189. mousewheel.wheelPrecision = value;
  48190. },
  48191. enumerable: true,
  48192. configurable: true
  48193. });
  48194. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48195. get: function () {
  48196. var mousewheel = this.inputs.attached["mousewheel"];
  48197. if (mousewheel)
  48198. return mousewheel.wheelDeltaPercentage;
  48199. return 0;
  48200. },
  48201. set: function (value) {
  48202. var mousewheel = this.inputs.attached["mousewheel"];
  48203. if (mousewheel)
  48204. mousewheel.wheelDeltaPercentage = value;
  48205. },
  48206. enumerable: true,
  48207. configurable: true
  48208. });
  48209. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48210. get: function () {
  48211. return this._bouncingBehavior;
  48212. },
  48213. enumerable: true,
  48214. configurable: true
  48215. });
  48216. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48217. get: function () {
  48218. return this._bouncingBehavior != null;
  48219. },
  48220. set: function (value) {
  48221. if (value === this.useBouncingBehavior) {
  48222. return;
  48223. }
  48224. if (value) {
  48225. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48226. this.addBehavior(this._bouncingBehavior);
  48227. }
  48228. else if (this._bouncingBehavior) {
  48229. this.removeBehavior(this._bouncingBehavior);
  48230. this._bouncingBehavior = null;
  48231. }
  48232. },
  48233. enumerable: true,
  48234. configurable: true
  48235. });
  48236. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48237. get: function () {
  48238. return this._framingBehavior;
  48239. },
  48240. enumerable: true,
  48241. configurable: true
  48242. });
  48243. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48244. get: function () {
  48245. return this._framingBehavior != null;
  48246. },
  48247. set: function (value) {
  48248. if (value === this.useFramingBehavior) {
  48249. return;
  48250. }
  48251. if (value) {
  48252. this._framingBehavior = new BABYLON.FramingBehavior();
  48253. this.addBehavior(this._framingBehavior);
  48254. }
  48255. else if (this._framingBehavior) {
  48256. this.removeBehavior(this._framingBehavior);
  48257. this._framingBehavior = null;
  48258. }
  48259. },
  48260. enumerable: true,
  48261. configurable: true
  48262. });
  48263. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48264. get: function () {
  48265. return this._autoRotationBehavior;
  48266. },
  48267. enumerable: true,
  48268. configurable: true
  48269. });
  48270. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48271. get: function () {
  48272. return this._autoRotationBehavior != null;
  48273. },
  48274. set: function (value) {
  48275. if (value === this.useAutoRotationBehavior) {
  48276. return;
  48277. }
  48278. if (value) {
  48279. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48280. this.addBehavior(this._autoRotationBehavior);
  48281. }
  48282. else if (this._autoRotationBehavior) {
  48283. this.removeBehavior(this._autoRotationBehavior);
  48284. this._autoRotationBehavior = null;
  48285. }
  48286. },
  48287. enumerable: true,
  48288. configurable: true
  48289. });
  48290. // Cache
  48291. ArcRotateCamera.prototype._initCache = function () {
  48292. _super.prototype._initCache.call(this);
  48293. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48294. this._cache.alpha = undefined;
  48295. this._cache.beta = undefined;
  48296. this._cache.radius = undefined;
  48297. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48298. };
  48299. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48300. if (!ignoreParentClass) {
  48301. _super.prototype._updateCache.call(this);
  48302. }
  48303. this._cache._target.copyFrom(this._getTargetPosition());
  48304. this._cache.alpha = this.alpha;
  48305. this._cache.beta = this.beta;
  48306. this._cache.radius = this.radius;
  48307. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48308. };
  48309. ArcRotateCamera.prototype._getTargetPosition = function () {
  48310. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48311. var pos = this._targetHost.getAbsolutePosition();
  48312. if (this._targetBoundingCenter) {
  48313. pos.addToRef(this._targetBoundingCenter, this._target);
  48314. }
  48315. else {
  48316. this._target.copyFrom(pos);
  48317. }
  48318. }
  48319. var lockedTargetPosition = this._getLockedTargetPosition();
  48320. if (lockedTargetPosition) {
  48321. return lockedTargetPosition;
  48322. }
  48323. return this._target;
  48324. };
  48325. ArcRotateCamera.prototype.storeState = function () {
  48326. this._storedAlpha = this.alpha;
  48327. this._storedBeta = this.beta;
  48328. this._storedRadius = this.radius;
  48329. this._storedTarget = this._getTargetPosition().clone();
  48330. return _super.prototype.storeState.call(this);
  48331. };
  48332. /**
  48333. * Restored camera state. You must call storeState() first
  48334. */
  48335. ArcRotateCamera.prototype._restoreStateValues = function () {
  48336. if (!_super.prototype._restoreStateValues.call(this)) {
  48337. return false;
  48338. }
  48339. this.alpha = this._storedAlpha;
  48340. this.beta = this._storedBeta;
  48341. this.radius = this._storedRadius;
  48342. this.setTarget(this._storedTarget.clone());
  48343. this.inertialAlphaOffset = 0;
  48344. this.inertialBetaOffset = 0;
  48345. this.inertialRadiusOffset = 0;
  48346. this.inertialPanningX = 0;
  48347. this.inertialPanningY = 0;
  48348. return true;
  48349. };
  48350. // Synchronized
  48351. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48352. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48353. return false;
  48354. return this._cache._target.equals(this._getTargetPosition())
  48355. && this._cache.alpha === this.alpha
  48356. && this._cache.beta === this.beta
  48357. && this._cache.radius === this.radius
  48358. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48359. };
  48360. // Methods
  48361. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48362. var _this = this;
  48363. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48364. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48365. this._useCtrlForPanning = useCtrlForPanning;
  48366. this._panningMouseButton = panningMouseButton;
  48367. this.inputs.attachElement(element, noPreventDefault);
  48368. this._reset = function () {
  48369. _this.inertialAlphaOffset = 0;
  48370. _this.inertialBetaOffset = 0;
  48371. _this.inertialRadiusOffset = 0;
  48372. _this.inertialPanningX = 0;
  48373. _this.inertialPanningY = 0;
  48374. };
  48375. };
  48376. ArcRotateCamera.prototype.detachControl = function (element) {
  48377. this.inputs.detachElement(element);
  48378. if (this._reset) {
  48379. this._reset();
  48380. }
  48381. };
  48382. ArcRotateCamera.prototype._checkInputs = function () {
  48383. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48384. if (this._collisionTriggered) {
  48385. return;
  48386. }
  48387. this.inputs.checkInputs();
  48388. // Inertia
  48389. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48390. if (this.getScene().useRightHandedSystem) {
  48391. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48392. }
  48393. else {
  48394. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48395. }
  48396. this.beta += this.inertialBetaOffset;
  48397. this.radius -= this.inertialRadiusOffset;
  48398. this.inertialAlphaOffset *= this.inertia;
  48399. this.inertialBetaOffset *= this.inertia;
  48400. this.inertialRadiusOffset *= this.inertia;
  48401. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48402. this.inertialAlphaOffset = 0;
  48403. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48404. this.inertialBetaOffset = 0;
  48405. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48406. this.inertialRadiusOffset = 0;
  48407. }
  48408. // Panning inertia
  48409. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48410. if (!this._localDirection) {
  48411. this._localDirection = BABYLON.Vector3.Zero();
  48412. this._transformedDirection = BABYLON.Vector3.Zero();
  48413. }
  48414. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48415. this._localDirection.multiplyInPlace(this.panningAxis);
  48416. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48417. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48418. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48419. if (!this.panningAxis.y) {
  48420. this._transformedDirection.y = 0;
  48421. }
  48422. if (!this._targetHost) {
  48423. if (this.panningDistanceLimit) {
  48424. this._transformedDirection.addInPlace(this._target);
  48425. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48426. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48427. this._target.copyFrom(this._transformedDirection);
  48428. }
  48429. }
  48430. else {
  48431. this._target.addInPlace(this._transformedDirection);
  48432. }
  48433. }
  48434. this.inertialPanningX *= this.panningInertia;
  48435. this.inertialPanningY *= this.panningInertia;
  48436. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48437. this.inertialPanningX = 0;
  48438. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48439. this.inertialPanningY = 0;
  48440. }
  48441. // Limits
  48442. this._checkLimits();
  48443. _super.prototype._checkInputs.call(this);
  48444. };
  48445. ArcRotateCamera.prototype._checkLimits = function () {
  48446. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48447. if (this.allowUpsideDown && this.beta > Math.PI) {
  48448. this.beta = this.beta - (2 * Math.PI);
  48449. }
  48450. }
  48451. else {
  48452. if (this.beta < this.lowerBetaLimit) {
  48453. this.beta = this.lowerBetaLimit;
  48454. }
  48455. }
  48456. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48457. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48458. this.beta = this.beta + (2 * Math.PI);
  48459. }
  48460. }
  48461. else {
  48462. if (this.beta > this.upperBetaLimit) {
  48463. this.beta = this.upperBetaLimit;
  48464. }
  48465. }
  48466. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48467. this.alpha = this.lowerAlphaLimit;
  48468. }
  48469. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48470. this.alpha = this.upperAlphaLimit;
  48471. }
  48472. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48473. this.radius = this.lowerRadiusLimit;
  48474. }
  48475. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48476. this.radius = this.upperRadiusLimit;
  48477. }
  48478. };
  48479. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48480. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48481. this.radius = this._computationVector.length();
  48482. if (this.radius === 0) {
  48483. this.radius = 0.0001; // Just to avoid division by zero
  48484. }
  48485. // Alpha
  48486. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48487. if (this._computationVector.z < 0) {
  48488. this.alpha = 2 * Math.PI - this.alpha;
  48489. }
  48490. // Beta
  48491. this.beta = Math.acos(this._computationVector.y / this.radius);
  48492. this._checkLimits();
  48493. };
  48494. ArcRotateCamera.prototype.setPosition = function (position) {
  48495. if (this.position.equals(position)) {
  48496. return;
  48497. }
  48498. this.position.copyFrom(position);
  48499. this.rebuildAnglesAndRadius();
  48500. };
  48501. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48502. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48503. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48504. if (target.getBoundingInfo) {
  48505. if (toBoundingCenter) {
  48506. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48507. }
  48508. else {
  48509. this._targetBoundingCenter = null;
  48510. }
  48511. this._targetHost = target;
  48512. this._target = this._getTargetPosition();
  48513. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48514. }
  48515. else {
  48516. var newTarget = target;
  48517. var currentTarget = this._getTargetPosition();
  48518. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48519. return;
  48520. }
  48521. this._targetHost = null;
  48522. this._target = newTarget;
  48523. this._targetBoundingCenter = null;
  48524. this.onMeshTargetChangedObservable.notifyObservers(null);
  48525. }
  48526. this.rebuildAnglesAndRadius();
  48527. };
  48528. ArcRotateCamera.prototype._getViewMatrix = function () {
  48529. // Compute
  48530. var cosa = Math.cos(this.alpha);
  48531. var sina = Math.sin(this.alpha);
  48532. var cosb = Math.cos(this.beta);
  48533. var sinb = Math.sin(this.beta);
  48534. if (sinb === 0) {
  48535. sinb = 0.0001;
  48536. }
  48537. var target = this._getTargetPosition();
  48538. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48539. target.addToRef(this._computationVector, this._newPosition);
  48540. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48541. if (!this._collider) {
  48542. this._collider = new BABYLON.Collider();
  48543. }
  48544. this._collider._radius = this.collisionRadius;
  48545. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48546. this._collisionTriggered = true;
  48547. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48548. }
  48549. else {
  48550. this.position.copyFrom(this._newPosition);
  48551. var up = this.upVector;
  48552. if (this.allowUpsideDown && sinb < 0) {
  48553. up = up.clone();
  48554. up = up.negate();
  48555. }
  48556. if (this.getScene().useRightHandedSystem) {
  48557. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48558. }
  48559. else {
  48560. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48561. }
  48562. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48563. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48564. }
  48565. this._currentTarget = target;
  48566. return this._viewMatrix;
  48567. };
  48568. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48569. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48570. meshes = meshes || this.getScene().meshes;
  48571. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48572. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48573. this.radius = distance * this.zoomOnFactor;
  48574. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48575. };
  48576. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48577. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48578. var meshesOrMinMaxVector;
  48579. var distance;
  48580. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  48581. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48582. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48583. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48584. }
  48585. else {
  48586. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48587. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48588. distance = minMaxVectorAndDistance.distance;
  48589. }
  48590. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48591. if (!doNotUpdateMaxZ) {
  48592. this.maxZ = distance * 2;
  48593. }
  48594. };
  48595. /**
  48596. * @override
  48597. * Override Camera.createRigCamera
  48598. */
  48599. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48600. var alphaShift = 0;
  48601. switch (this.cameraRigMode) {
  48602. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48603. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48604. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48605. case BABYLON.Camera.RIG_MODE_VR:
  48606. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48607. break;
  48608. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48609. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48610. break;
  48611. }
  48612. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48613. rigCam._cameraRigParams = {};
  48614. return rigCam;
  48615. };
  48616. /**
  48617. * @override
  48618. * Override Camera._updateRigCameras
  48619. */
  48620. ArcRotateCamera.prototype._updateRigCameras = function () {
  48621. var camLeft = this._rigCameras[0];
  48622. var camRight = this._rigCameras[1];
  48623. camLeft.beta = camRight.beta = this.beta;
  48624. camLeft.radius = camRight.radius = this.radius;
  48625. switch (this.cameraRigMode) {
  48626. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48628. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48629. case BABYLON.Camera.RIG_MODE_VR:
  48630. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48631. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48632. break;
  48633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48634. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48635. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48636. break;
  48637. }
  48638. _super.prototype._updateRigCameras.call(this);
  48639. };
  48640. ArcRotateCamera.prototype.dispose = function () {
  48641. this.inputs.clear();
  48642. _super.prototype.dispose.call(this);
  48643. };
  48644. ArcRotateCamera.prototype.getClassName = function () {
  48645. return "ArcRotateCamera";
  48646. };
  48647. __decorate([
  48648. BABYLON.serialize()
  48649. ], ArcRotateCamera.prototype, "alpha", void 0);
  48650. __decorate([
  48651. BABYLON.serialize()
  48652. ], ArcRotateCamera.prototype, "beta", void 0);
  48653. __decorate([
  48654. BABYLON.serialize()
  48655. ], ArcRotateCamera.prototype, "radius", void 0);
  48656. __decorate([
  48657. BABYLON.serializeAsVector3("target")
  48658. ], ArcRotateCamera.prototype, "_target", void 0);
  48659. __decorate([
  48660. BABYLON.serialize()
  48661. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48662. __decorate([
  48663. BABYLON.serialize()
  48664. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48665. __decorate([
  48666. BABYLON.serialize()
  48667. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48668. __decorate([
  48669. BABYLON.serialize()
  48670. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48671. __decorate([
  48672. BABYLON.serialize()
  48673. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48674. __decorate([
  48675. BABYLON.serialize()
  48676. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48677. __decorate([
  48678. BABYLON.serialize()
  48679. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48680. __decorate([
  48681. BABYLON.serialize()
  48682. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48683. __decorate([
  48684. BABYLON.serialize()
  48685. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48686. __decorate([
  48687. BABYLON.serialize()
  48688. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48689. __decorate([
  48690. BABYLON.serialize()
  48691. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48692. __decorate([
  48693. BABYLON.serialize()
  48694. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48695. __decorate([
  48696. BABYLON.serialize()
  48697. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48698. __decorate([
  48699. BABYLON.serializeAsVector3()
  48700. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48701. __decorate([
  48702. BABYLON.serialize()
  48703. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48704. __decorate([
  48705. BABYLON.serialize()
  48706. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48707. __decorate([
  48708. BABYLON.serialize()
  48709. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48710. return ArcRotateCamera;
  48711. }(BABYLON.TargetCamera));
  48712. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48713. })(BABYLON || (BABYLON = {}));
  48714. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48715. "use strict";
  48716. var BABYLON;
  48717. (function (BABYLON) {
  48718. /**
  48719. * The HemisphericLight simulates the ambient environment light,
  48720. * so the passed direction is the light reflection direction, not the incoming direction.
  48721. */
  48722. var HemisphericLight = /** @class */ (function (_super) {
  48723. __extends(HemisphericLight, _super);
  48724. /**
  48725. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48726. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48727. * The HemisphericLight can't cast shadows.
  48728. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48729. * @param name The friendly name of the light
  48730. * @param direction The direction of the light reflection
  48731. * @param scene The scene the light belongs to
  48732. */
  48733. function HemisphericLight(name, direction, scene) {
  48734. var _this = _super.call(this, name, scene) || this;
  48735. /**
  48736. * The groundColor is the light in the opposite direction to the one specified during creation.
  48737. * 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.
  48738. */
  48739. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48740. _this.direction = direction || BABYLON.Vector3.Up();
  48741. return _this;
  48742. }
  48743. HemisphericLight.prototype._buildUniformLayout = function () {
  48744. this._uniformBuffer.addUniform("vLightData", 4);
  48745. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48746. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48747. this._uniformBuffer.addUniform("vLightGround", 3);
  48748. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48749. this._uniformBuffer.addUniform("depthValues", 2);
  48750. this._uniformBuffer.create();
  48751. };
  48752. /**
  48753. * Returns the string "HemisphericLight".
  48754. * @return The class name
  48755. */
  48756. HemisphericLight.prototype.getClassName = function () {
  48757. return "HemisphericLight";
  48758. };
  48759. /**
  48760. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48761. * Returns the updated direction.
  48762. * @param target The target the direction should point to
  48763. * @return The computed direction
  48764. */
  48765. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48766. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48767. return this.direction;
  48768. };
  48769. /**
  48770. * Returns the shadow generator associated to the light.
  48771. * @returns Always null for hemispheric lights because it does not support shadows.
  48772. */
  48773. HemisphericLight.prototype.getShadowGenerator = function () {
  48774. return null;
  48775. };
  48776. /**
  48777. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48778. * @param effect The effect to update
  48779. * @param lightIndex The index of the light in the effect to update
  48780. * @returns The hemispheric light
  48781. */
  48782. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48783. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48784. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48785. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48786. return this;
  48787. };
  48788. /**
  48789. * @ignore internal use only.
  48790. */
  48791. HemisphericLight.prototype._getWorldMatrix = function () {
  48792. if (!this._worldMatrix) {
  48793. this._worldMatrix = BABYLON.Matrix.Identity();
  48794. }
  48795. return this._worldMatrix;
  48796. };
  48797. /**
  48798. * Returns the integer 3.
  48799. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48800. */
  48801. HemisphericLight.prototype.getTypeID = function () {
  48802. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48803. };
  48804. __decorate([
  48805. BABYLON.serializeAsColor3()
  48806. ], HemisphericLight.prototype, "groundColor", void 0);
  48807. __decorate([
  48808. BABYLON.serializeAsVector3()
  48809. ], HemisphericLight.prototype, "direction", void 0);
  48810. return HemisphericLight;
  48811. }(BABYLON.Light));
  48812. BABYLON.HemisphericLight = HemisphericLight;
  48813. })(BABYLON || (BABYLON = {}));
  48814. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48815. "use strict";
  48816. var BABYLON;
  48817. (function (BABYLON) {
  48818. /**
  48819. * Base implementation IShadowLight
  48820. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48821. */
  48822. var ShadowLight = /** @class */ (function (_super) {
  48823. __extends(ShadowLight, _super);
  48824. function ShadowLight() {
  48825. var _this = _super !== null && _super.apply(this, arguments) || this;
  48826. _this._needProjectionMatrixCompute = true;
  48827. return _this;
  48828. }
  48829. ShadowLight.prototype._setPosition = function (value) {
  48830. this._position = value;
  48831. };
  48832. Object.defineProperty(ShadowLight.prototype, "position", {
  48833. /**
  48834. * Sets the position the shadow will be casted from. Also use as the light position for both
  48835. * point and spot lights.
  48836. */
  48837. get: function () {
  48838. return this._position;
  48839. },
  48840. /**
  48841. * Sets the position the shadow will be casted from. Also use as the light position for both
  48842. * point and spot lights.
  48843. */
  48844. set: function (value) {
  48845. this._setPosition(value);
  48846. },
  48847. enumerable: true,
  48848. configurable: true
  48849. });
  48850. ShadowLight.prototype._setDirection = function (value) {
  48851. this._direction = value;
  48852. };
  48853. Object.defineProperty(ShadowLight.prototype, "direction", {
  48854. /**
  48855. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48856. * Also use as the light direction on spot and directional lights.
  48857. */
  48858. get: function () {
  48859. return this._direction;
  48860. },
  48861. /**
  48862. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48863. * Also use as the light direction on spot and directional lights.
  48864. */
  48865. set: function (value) {
  48866. this._setDirection(value);
  48867. },
  48868. enumerable: true,
  48869. configurable: true
  48870. });
  48871. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48872. /**
  48873. * Gets the shadow projection clipping minimum z value.
  48874. */
  48875. get: function () {
  48876. return this._shadowMinZ;
  48877. },
  48878. /**
  48879. * Sets the shadow projection clipping minimum z value.
  48880. */
  48881. set: function (value) {
  48882. this._shadowMinZ = value;
  48883. this.forceProjectionMatrixCompute();
  48884. },
  48885. enumerable: true,
  48886. configurable: true
  48887. });
  48888. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48889. /**
  48890. * Sets the shadow projection clipping maximum z value.
  48891. */
  48892. get: function () {
  48893. return this._shadowMaxZ;
  48894. },
  48895. /**
  48896. * Gets the shadow projection clipping maximum z value.
  48897. */
  48898. set: function (value) {
  48899. this._shadowMaxZ = value;
  48900. this.forceProjectionMatrixCompute();
  48901. },
  48902. enumerable: true,
  48903. configurable: true
  48904. });
  48905. /**
  48906. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48907. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48908. */
  48909. ShadowLight.prototype.computeTransformedInformation = function () {
  48910. if (this.parent && this.parent.getWorldMatrix) {
  48911. if (!this.transformedPosition) {
  48912. this.transformedPosition = BABYLON.Vector3.Zero();
  48913. }
  48914. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48915. // In case the direction is present.
  48916. if (this.direction) {
  48917. if (!this.transformedDirection) {
  48918. this.transformedDirection = BABYLON.Vector3.Zero();
  48919. }
  48920. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48921. }
  48922. return true;
  48923. }
  48924. return false;
  48925. };
  48926. /**
  48927. * Return the depth scale used for the shadow map.
  48928. * @returns the depth scale.
  48929. */
  48930. ShadowLight.prototype.getDepthScale = function () {
  48931. return 50.0;
  48932. };
  48933. /**
  48934. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48935. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48936. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48937. */
  48938. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48939. return this.transformedDirection ? this.transformedDirection : this.direction;
  48940. };
  48941. /**
  48942. * Returns the ShadowLight absolute position in the World.
  48943. * @returns the position vector in world space
  48944. */
  48945. ShadowLight.prototype.getAbsolutePosition = function () {
  48946. return this.transformedPosition ? this.transformedPosition : this.position;
  48947. };
  48948. /**
  48949. * Sets the ShadowLight direction toward the passed target.
  48950. * @param target The point tot target in local space
  48951. * @returns the updated ShadowLight direction
  48952. */
  48953. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48954. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48955. return this.direction;
  48956. };
  48957. /**
  48958. * Returns the light rotation in euler definition.
  48959. * @returns the x y z rotation in local space.
  48960. */
  48961. ShadowLight.prototype.getRotation = function () {
  48962. this.direction.normalize();
  48963. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48964. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48965. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48966. };
  48967. /**
  48968. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48969. * @returns true if a cube texture needs to be use
  48970. */
  48971. ShadowLight.prototype.needCube = function () {
  48972. return false;
  48973. };
  48974. /**
  48975. * Detects if the projection matrix requires to be recomputed this frame.
  48976. * @returns true if it requires to be recomputed otherwise, false.
  48977. */
  48978. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48979. return this._needProjectionMatrixCompute;
  48980. };
  48981. /**
  48982. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48983. */
  48984. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48985. this._needProjectionMatrixCompute = true;
  48986. };
  48987. /**
  48988. * Get the world matrix of the sahdow lights.
  48989. * @ignore Internal Use Only
  48990. */
  48991. ShadowLight.prototype._getWorldMatrix = function () {
  48992. if (!this._worldMatrix) {
  48993. this._worldMatrix = BABYLON.Matrix.Identity();
  48994. }
  48995. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48996. return this._worldMatrix;
  48997. };
  48998. /**
  48999. * Gets the minZ used for shadow according to both the scene and the light.
  49000. * @param activeCamera The camera we are returning the min for
  49001. * @returns the depth min z
  49002. */
  49003. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49004. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49005. };
  49006. /**
  49007. * Gets the maxZ used for shadow according to both the scene and the light.
  49008. * @param activeCamera The camera we are returning the max for
  49009. * @returns the depth max z
  49010. */
  49011. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49012. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49013. };
  49014. /**
  49015. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49016. * @param matrix The materix to updated with the projection information
  49017. * @param viewMatrix The transform matrix of the light
  49018. * @param renderList The list of mesh to render in the map
  49019. * @returns The current light
  49020. */
  49021. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49022. if (this.customProjectionMatrixBuilder) {
  49023. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49024. }
  49025. else {
  49026. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49027. }
  49028. return this;
  49029. };
  49030. __decorate([
  49031. BABYLON.serializeAsVector3()
  49032. ], ShadowLight.prototype, "position", null);
  49033. __decorate([
  49034. BABYLON.serializeAsVector3()
  49035. ], ShadowLight.prototype, "direction", null);
  49036. __decorate([
  49037. BABYLON.serialize()
  49038. ], ShadowLight.prototype, "shadowMinZ", null);
  49039. __decorate([
  49040. BABYLON.serialize()
  49041. ], ShadowLight.prototype, "shadowMaxZ", null);
  49042. return ShadowLight;
  49043. }(BABYLON.Light));
  49044. BABYLON.ShadowLight = ShadowLight;
  49045. })(BABYLON || (BABYLON = {}));
  49046. //# sourceMappingURL=babylon.shadowLight.js.map
  49047. "use strict";
  49048. var BABYLON;
  49049. (function (BABYLON) {
  49050. /**
  49051. * A point light is a light defined by an unique point in world space.
  49052. * The light is emitted in every direction from this point.
  49053. * A good example of a point light is a standard light bulb.
  49054. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49055. */
  49056. var PointLight = /** @class */ (function (_super) {
  49057. __extends(PointLight, _super);
  49058. /**
  49059. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49060. * A PointLight emits the light in every direction.
  49061. * It can cast shadows.
  49062. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49063. * ```javascript
  49064. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49065. * ```
  49066. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49067. * @param name The light friendly name
  49068. * @param position The position of the point light in the scene
  49069. * @param scene The scene the lights belongs to
  49070. */
  49071. function PointLight(name, position, scene) {
  49072. var _this = _super.call(this, name, scene) || this;
  49073. _this._shadowAngle = Math.PI / 2;
  49074. _this.position = position;
  49075. return _this;
  49076. }
  49077. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49078. /**
  49079. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49080. * This specifies what angle the shadow will use to be created.
  49081. *
  49082. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49083. */
  49084. get: function () {
  49085. return this._shadowAngle;
  49086. },
  49087. /**
  49088. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49089. * This specifies what angle the shadow will use to be created.
  49090. *
  49091. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49092. */
  49093. set: function (value) {
  49094. this._shadowAngle = value;
  49095. this.forceProjectionMatrixCompute();
  49096. },
  49097. enumerable: true,
  49098. configurable: true
  49099. });
  49100. Object.defineProperty(PointLight.prototype, "direction", {
  49101. /**
  49102. * Gets the direction if it has been set.
  49103. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49104. */
  49105. get: function () {
  49106. return this._direction;
  49107. },
  49108. /**
  49109. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49110. */
  49111. set: function (value) {
  49112. var previousNeedCube = this.needCube();
  49113. this._direction = value;
  49114. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49115. this._shadowGenerator.recreateShadowMap();
  49116. }
  49117. },
  49118. enumerable: true,
  49119. configurable: true
  49120. });
  49121. /**
  49122. * Returns the string "PointLight"
  49123. * @returns the class name
  49124. */
  49125. PointLight.prototype.getClassName = function () {
  49126. return "PointLight";
  49127. };
  49128. /**
  49129. * Returns the integer 0.
  49130. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49131. */
  49132. PointLight.prototype.getTypeID = function () {
  49133. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49134. };
  49135. /**
  49136. * Specifies wether or not the shadowmap should be a cube texture.
  49137. * @returns true if the shadowmap needs to be a cube texture.
  49138. */
  49139. PointLight.prototype.needCube = function () {
  49140. return !this.direction;
  49141. };
  49142. /**
  49143. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49144. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49145. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49146. */
  49147. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49148. if (this.direction) {
  49149. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49150. }
  49151. else {
  49152. switch (faceIndex) {
  49153. case 0:
  49154. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49155. case 1:
  49156. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49157. case 2:
  49158. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49159. case 3:
  49160. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49161. case 4:
  49162. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49163. case 5:
  49164. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49165. }
  49166. }
  49167. return BABYLON.Vector3.Zero();
  49168. };
  49169. /**
  49170. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49171. * - fov = PI / 2
  49172. * - aspect ratio : 1.0
  49173. * - z-near and far equal to the active camera minZ and maxZ.
  49174. * Returns the PointLight.
  49175. */
  49176. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49177. var activeCamera = this.getScene().activeCamera;
  49178. if (!activeCamera) {
  49179. return;
  49180. }
  49181. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49182. };
  49183. PointLight.prototype._buildUniformLayout = function () {
  49184. this._uniformBuffer.addUniform("vLightData", 4);
  49185. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49186. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49187. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49188. this._uniformBuffer.addUniform("depthValues", 2);
  49189. this._uniformBuffer.create();
  49190. };
  49191. /**
  49192. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49193. * @param effect The effect to update
  49194. * @param lightIndex The index of the light in the effect to update
  49195. * @returns The point light
  49196. */
  49197. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49198. if (this.computeTransformedInformation()) {
  49199. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49200. return this;
  49201. }
  49202. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49203. return this;
  49204. };
  49205. __decorate([
  49206. BABYLON.serialize()
  49207. ], PointLight.prototype, "shadowAngle", null);
  49208. return PointLight;
  49209. }(BABYLON.ShadowLight));
  49210. BABYLON.PointLight = PointLight;
  49211. })(BABYLON || (BABYLON = {}));
  49212. //# sourceMappingURL=babylon.pointLight.js.map
  49213. "use strict";
  49214. var BABYLON;
  49215. (function (BABYLON) {
  49216. /**
  49217. * A directional light is defined by a direction (what a surprise!).
  49218. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49219. * 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.
  49220. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49221. */
  49222. var DirectionalLight = /** @class */ (function (_super) {
  49223. __extends(DirectionalLight, _super);
  49224. /**
  49225. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49226. * The directional light is emitted from everywhere in the given direction.
  49227. * It can cast shawdows.
  49228. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49229. * @param name The friendly name of the light
  49230. * @param direction The direction of the light
  49231. * @param scene The scene the light belongs to
  49232. */
  49233. function DirectionalLight(name, direction, scene) {
  49234. var _this = _super.call(this, name, scene) || this;
  49235. _this._shadowFrustumSize = 0;
  49236. _this._shadowOrthoScale = 0.1;
  49237. /**
  49238. * Automatically compute the projection matrix to best fit (including all the casters)
  49239. * on each frame.
  49240. */
  49241. _this.autoUpdateExtends = true;
  49242. // Cache
  49243. _this._orthoLeft = Number.MAX_VALUE;
  49244. _this._orthoRight = Number.MIN_VALUE;
  49245. _this._orthoTop = Number.MIN_VALUE;
  49246. _this._orthoBottom = Number.MAX_VALUE;
  49247. _this.position = direction.scale(-1.0);
  49248. _this.direction = direction;
  49249. return _this;
  49250. }
  49251. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49252. /**
  49253. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49254. */
  49255. get: function () {
  49256. return this._shadowFrustumSize;
  49257. },
  49258. /**
  49259. * Specifies a fix frustum size for the shadow generation.
  49260. */
  49261. set: function (value) {
  49262. this._shadowFrustumSize = value;
  49263. this.forceProjectionMatrixCompute();
  49264. },
  49265. enumerable: true,
  49266. configurable: true
  49267. });
  49268. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49269. /**
  49270. * Gets the shadow projection scale against the optimal computed one.
  49271. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49272. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49273. */
  49274. get: function () {
  49275. return this._shadowOrthoScale;
  49276. },
  49277. /**
  49278. * Sets the shadow projection scale against the optimal computed one.
  49279. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49280. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49281. */
  49282. set: function (value) {
  49283. this._shadowOrthoScale = value;
  49284. this.forceProjectionMatrixCompute();
  49285. },
  49286. enumerable: true,
  49287. configurable: true
  49288. });
  49289. /**
  49290. * Returns the string "DirectionalLight".
  49291. * @return The class name
  49292. */
  49293. DirectionalLight.prototype.getClassName = function () {
  49294. return "DirectionalLight";
  49295. };
  49296. /**
  49297. * Returns the integer 1.
  49298. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49299. */
  49300. DirectionalLight.prototype.getTypeID = function () {
  49301. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49302. };
  49303. /**
  49304. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49305. * Returns the DirectionalLight Shadow projection matrix.
  49306. */
  49307. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49308. if (this.shadowFrustumSize > 0) {
  49309. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49310. }
  49311. else {
  49312. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49313. }
  49314. };
  49315. /**
  49316. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49317. * Returns the DirectionalLight Shadow projection matrix.
  49318. */
  49319. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49320. var activeCamera = this.getScene().activeCamera;
  49321. if (!activeCamera) {
  49322. return;
  49323. }
  49324. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49325. };
  49326. /**
  49327. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49328. * Returns the DirectionalLight Shadow projection matrix.
  49329. */
  49330. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49331. var activeCamera = this.getScene().activeCamera;
  49332. if (!activeCamera) {
  49333. return;
  49334. }
  49335. // Check extends
  49336. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49337. var tempVector3 = BABYLON.Vector3.Zero();
  49338. this._orthoLeft = Number.MAX_VALUE;
  49339. this._orthoRight = Number.MIN_VALUE;
  49340. this._orthoTop = Number.MIN_VALUE;
  49341. this._orthoBottom = Number.MAX_VALUE;
  49342. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49343. var mesh = renderList[meshIndex];
  49344. if (!mesh) {
  49345. continue;
  49346. }
  49347. var boundingInfo = mesh.getBoundingInfo();
  49348. var boundingBox = boundingInfo.boundingBox;
  49349. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49350. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49351. if (tempVector3.x < this._orthoLeft)
  49352. this._orthoLeft = tempVector3.x;
  49353. if (tempVector3.y < this._orthoBottom)
  49354. this._orthoBottom = tempVector3.y;
  49355. if (tempVector3.x > this._orthoRight)
  49356. this._orthoRight = tempVector3.x;
  49357. if (tempVector3.y > this._orthoTop)
  49358. this._orthoTop = tempVector3.y;
  49359. }
  49360. }
  49361. }
  49362. var xOffset = this._orthoRight - this._orthoLeft;
  49363. var yOffset = this._orthoTop - this._orthoBottom;
  49364. 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);
  49365. };
  49366. DirectionalLight.prototype._buildUniformLayout = function () {
  49367. this._uniformBuffer.addUniform("vLightData", 4);
  49368. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49369. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49370. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49371. this._uniformBuffer.addUniform("depthValues", 2);
  49372. this._uniformBuffer.create();
  49373. };
  49374. /**
  49375. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49376. * @param effect The effect to update
  49377. * @param lightIndex The index of the light in the effect to update
  49378. * @returns The directional light
  49379. */
  49380. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49381. if (this.computeTransformedInformation()) {
  49382. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49383. return this;
  49384. }
  49385. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49386. return this;
  49387. };
  49388. /**
  49389. * Gets the minZ used for shadow according to both the scene and the light.
  49390. *
  49391. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49392. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49393. * @param activeCamera The camera we are returning the min for
  49394. * @returns the depth min z
  49395. */
  49396. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49397. return 1;
  49398. };
  49399. /**
  49400. * Gets the maxZ used for shadow according to both the scene and the light.
  49401. *
  49402. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49403. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49404. * @param activeCamera The camera we are returning the max for
  49405. * @returns the depth max z
  49406. */
  49407. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49408. return 1;
  49409. };
  49410. __decorate([
  49411. BABYLON.serialize()
  49412. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49413. __decorate([
  49414. BABYLON.serialize()
  49415. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49416. __decorate([
  49417. BABYLON.serialize()
  49418. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49419. return DirectionalLight;
  49420. }(BABYLON.ShadowLight));
  49421. BABYLON.DirectionalLight = DirectionalLight;
  49422. })(BABYLON || (BABYLON = {}));
  49423. //# sourceMappingURL=babylon.directionalLight.js.map
  49424. "use strict";
  49425. var BABYLON;
  49426. (function (BABYLON) {
  49427. /**
  49428. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49429. * These values define a cone of light starting from the position, emitting toward the direction.
  49430. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49431. * and the exponent defines the speed of the decay of the light with distance (reach).
  49432. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49433. */
  49434. var SpotLight = /** @class */ (function (_super) {
  49435. __extends(SpotLight, _super);
  49436. /**
  49437. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49438. * It can cast shadows.
  49439. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49440. * @param name The light friendly name
  49441. * @param position The position of the spot light in the scene
  49442. * @param direction The direction of the light in the scene
  49443. * @param angle The cone angle of the light in Radians
  49444. * @param exponent The light decay speed with the distance from the emission spot
  49445. * @param scene The scene the lights belongs to
  49446. */
  49447. function SpotLight(name, position, direction, angle, exponent, scene) {
  49448. var _this = _super.call(this, name, scene) || this;
  49449. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49450. _this._projectionTextureLightNear = 1e-6;
  49451. _this._projectionTextureLightFar = 1000.0;
  49452. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49453. _this._projectionTextureViewLightDirty = true;
  49454. _this._projectionTextureProjectionLightDirty = true;
  49455. _this._projectionTextureDirty = true;
  49456. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49457. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49458. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49459. _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);
  49460. _this.position = position;
  49461. _this.direction = direction;
  49462. _this.angle = angle;
  49463. _this.exponent = exponent;
  49464. return _this;
  49465. }
  49466. Object.defineProperty(SpotLight.prototype, "angle", {
  49467. /**
  49468. * Gets the cone angle of the spot light in Radians.
  49469. */
  49470. get: function () {
  49471. return this._angle;
  49472. },
  49473. /**
  49474. * Sets the cone angle of the spot light in Radians.
  49475. */
  49476. set: function (value) {
  49477. this._angle = value;
  49478. this._projectionTextureProjectionLightDirty = true;
  49479. this.forceProjectionMatrixCompute();
  49480. },
  49481. enumerable: true,
  49482. configurable: true
  49483. });
  49484. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49485. /**
  49486. * Allows scaling the angle of the light for shadow generation only.
  49487. */
  49488. get: function () {
  49489. return this._shadowAngleScale;
  49490. },
  49491. /**
  49492. * Allows scaling the angle of the light for shadow generation only.
  49493. */
  49494. set: function (value) {
  49495. this._shadowAngleScale = value;
  49496. this.forceProjectionMatrixCompute();
  49497. },
  49498. enumerable: true,
  49499. configurable: true
  49500. });
  49501. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49502. /**
  49503. * Allows reading the projecton texture
  49504. */
  49505. get: function () {
  49506. return this._projectionTextureMatrix;
  49507. },
  49508. enumerable: true,
  49509. configurable: true
  49510. });
  49511. ;
  49512. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49513. /**
  49514. * Gets the near clip of the Spotlight for texture projection.
  49515. */
  49516. get: function () {
  49517. return this._projectionTextureLightNear;
  49518. },
  49519. /**
  49520. * Sets the near clip of the Spotlight for texture projection.
  49521. */
  49522. set: function (value) {
  49523. this._projectionTextureLightNear = value;
  49524. this._projectionTextureProjectionLightDirty = true;
  49525. },
  49526. enumerable: true,
  49527. configurable: true
  49528. });
  49529. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49530. /**
  49531. * Gets the far clip of the Spotlight for texture projection.
  49532. */
  49533. get: function () {
  49534. return this._projectionTextureLightFar;
  49535. },
  49536. /**
  49537. * Sets the far clip of the Spotlight for texture projection.
  49538. */
  49539. set: function (value) {
  49540. this._projectionTextureLightFar = value;
  49541. this._projectionTextureProjectionLightDirty = true;
  49542. },
  49543. enumerable: true,
  49544. configurable: true
  49545. });
  49546. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49547. /**
  49548. * Gets the Up vector of the Spotlight for texture projection.
  49549. */
  49550. get: function () {
  49551. return this._projectionTextureUpDirection;
  49552. },
  49553. /**
  49554. * Sets the Up vector of the Spotlight for texture projection.
  49555. */
  49556. set: function (value) {
  49557. this._projectionTextureUpDirection = value;
  49558. this._projectionTextureProjectionLightDirty = true;
  49559. },
  49560. enumerable: true,
  49561. configurable: true
  49562. });
  49563. ;
  49564. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49565. /**
  49566. * Gets the projection texture of the light.
  49567. */
  49568. get: function () {
  49569. return this._projectionTexture;
  49570. },
  49571. /**
  49572. * Sets the projection texture of the light.
  49573. */
  49574. set: function (value) {
  49575. this._projectionTexture = value;
  49576. this._projectionTextureDirty = true;
  49577. },
  49578. enumerable: true,
  49579. configurable: true
  49580. });
  49581. /**
  49582. * Returns the string "SpotLight".
  49583. * @returns the class name
  49584. */
  49585. SpotLight.prototype.getClassName = function () {
  49586. return "SpotLight";
  49587. };
  49588. /**
  49589. * Returns the integer 2.
  49590. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49591. */
  49592. SpotLight.prototype.getTypeID = function () {
  49593. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49594. };
  49595. /**
  49596. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49597. */
  49598. SpotLight.prototype._setDirection = function (value) {
  49599. _super.prototype._setDirection.call(this, value);
  49600. this._projectionTextureViewLightDirty = true;
  49601. };
  49602. /**
  49603. * Overrides the position setter to recompute the projection texture view light Matrix.
  49604. */
  49605. SpotLight.prototype._setPosition = function (value) {
  49606. _super.prototype._setPosition.call(this, value);
  49607. this._projectionTextureViewLightDirty = true;
  49608. };
  49609. /**
  49610. * 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.
  49611. * Returns the SpotLight.
  49612. */
  49613. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49614. var activeCamera = this.getScene().activeCamera;
  49615. if (!activeCamera) {
  49616. return;
  49617. }
  49618. this._shadowAngleScale = this._shadowAngleScale || 1;
  49619. var angle = this._shadowAngleScale * this._angle;
  49620. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49621. };
  49622. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49623. this._projectionTextureViewLightDirty = false;
  49624. this._projectionTextureDirty = true;
  49625. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49626. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49627. };
  49628. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49629. this._projectionTextureProjectionLightDirty = false;
  49630. this._projectionTextureDirty = true;
  49631. var light_far = this.projectionTextureLightFar;
  49632. var light_near = this.projectionTextureLightNear;
  49633. var P = light_far / (light_far - light_near);
  49634. var Q = -P * light_near;
  49635. var S = 1.0 / Math.tan(this._angle / 2.0);
  49636. var A = 1.0;
  49637. 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);
  49638. };
  49639. /**
  49640. * Main function for light texture projection matrix computing.
  49641. */
  49642. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49643. this._projectionTextureDirty = false;
  49644. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49645. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49646. };
  49647. SpotLight.prototype._buildUniformLayout = function () {
  49648. this._uniformBuffer.addUniform("vLightData", 4);
  49649. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49650. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49651. this._uniformBuffer.addUniform("vLightDirection", 3);
  49652. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49653. this._uniformBuffer.addUniform("depthValues", 2);
  49654. this._uniformBuffer.create();
  49655. };
  49656. /**
  49657. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49658. * @param effect The effect to update
  49659. * @param lightIndex The index of the light in the effect to update
  49660. * @returns The spot light
  49661. */
  49662. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49663. var normalizeDirection;
  49664. if (this.computeTransformedInformation()) {
  49665. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49666. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49667. }
  49668. else {
  49669. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49670. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49671. }
  49672. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49673. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49674. if (this._projectionTextureViewLightDirty) {
  49675. this._computeProjectionTextureViewLightMatrix();
  49676. }
  49677. if (this._projectionTextureProjectionLightDirty) {
  49678. this._computeProjectionTextureProjectionLightMatrix();
  49679. }
  49680. if (this._projectionTextureDirty) {
  49681. this._computeProjectionTextureMatrix();
  49682. }
  49683. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49684. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49685. }
  49686. return this;
  49687. };
  49688. /**
  49689. * Disposes the light and the associated resources.
  49690. */
  49691. SpotLight.prototype.dispose = function () {
  49692. _super.prototype.dispose.call(this);
  49693. if (this._projectionTexture) {
  49694. this._projectionTexture.dispose();
  49695. }
  49696. };
  49697. __decorate([
  49698. BABYLON.serialize()
  49699. ], SpotLight.prototype, "angle", null);
  49700. __decorate([
  49701. BABYLON.serialize()
  49702. ], SpotLight.prototype, "shadowAngleScale", null);
  49703. __decorate([
  49704. BABYLON.serialize()
  49705. ], SpotLight.prototype, "exponent", void 0);
  49706. __decorate([
  49707. BABYLON.serialize()
  49708. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49709. __decorate([
  49710. BABYLON.serialize()
  49711. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49712. __decorate([
  49713. BABYLON.serialize()
  49714. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49715. __decorate([
  49716. BABYLON.serializeAsTexture("projectedLightTexture")
  49717. ], SpotLight.prototype, "_projectionTexture", void 0);
  49718. return SpotLight;
  49719. }(BABYLON.ShadowLight));
  49720. BABYLON.SpotLight = SpotLight;
  49721. })(BABYLON || (BABYLON = {}));
  49722. //# sourceMappingURL=babylon.spotLight.js.map
  49723. "use strict";
  49724. var BABYLON;
  49725. (function (BABYLON) {
  49726. /**
  49727. * Class used to override all child animations of a given target
  49728. */
  49729. var AnimationPropertiesOverride = /** @class */ (function () {
  49730. function AnimationPropertiesOverride() {
  49731. /**
  49732. * Gets or sets a value indicating if animation blending must be used
  49733. */
  49734. this.enableBlending = false;
  49735. /**
  49736. * Gets or sets the blending speed to use when enableBlending is true
  49737. */
  49738. this.blendingSpeed = 0.01;
  49739. /**
  49740. * Gets or sets the default loop mode to use
  49741. */
  49742. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49743. }
  49744. return AnimationPropertiesOverride;
  49745. }());
  49746. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49747. })(BABYLON || (BABYLON = {}));
  49748. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49749. "use strict";
  49750. var BABYLON;
  49751. (function (BABYLON) {
  49752. var AnimationRange = /** @class */ (function () {
  49753. function AnimationRange(name, from, to) {
  49754. this.name = name;
  49755. this.from = from;
  49756. this.to = to;
  49757. }
  49758. AnimationRange.prototype.clone = function () {
  49759. return new AnimationRange(this.name, this.from, this.to);
  49760. };
  49761. return AnimationRange;
  49762. }());
  49763. BABYLON.AnimationRange = AnimationRange;
  49764. /**
  49765. * Composed of a frame, and an action function
  49766. */
  49767. var AnimationEvent = /** @class */ (function () {
  49768. function AnimationEvent(frame, action, onlyOnce) {
  49769. this.frame = frame;
  49770. this.action = action;
  49771. this.onlyOnce = onlyOnce;
  49772. this.isDone = false;
  49773. }
  49774. return AnimationEvent;
  49775. }());
  49776. BABYLON.AnimationEvent = AnimationEvent;
  49777. var PathCursor = /** @class */ (function () {
  49778. function PathCursor(path) {
  49779. this.path = path;
  49780. this._onchange = new Array();
  49781. this.value = 0;
  49782. this.animations = new Array();
  49783. }
  49784. PathCursor.prototype.getPoint = function () {
  49785. var point = this.path.getPointAtLengthPosition(this.value);
  49786. return new BABYLON.Vector3(point.x, 0, point.y);
  49787. };
  49788. PathCursor.prototype.moveAhead = function (step) {
  49789. if (step === void 0) { step = 0.002; }
  49790. this.move(step);
  49791. return this;
  49792. };
  49793. PathCursor.prototype.moveBack = function (step) {
  49794. if (step === void 0) { step = 0.002; }
  49795. this.move(-step);
  49796. return this;
  49797. };
  49798. PathCursor.prototype.move = function (step) {
  49799. if (Math.abs(step) > 1) {
  49800. throw "step size should be less than 1.";
  49801. }
  49802. this.value += step;
  49803. this.ensureLimits();
  49804. this.raiseOnChange();
  49805. return this;
  49806. };
  49807. PathCursor.prototype.ensureLimits = function () {
  49808. while (this.value > 1) {
  49809. this.value -= 1;
  49810. }
  49811. while (this.value < 0) {
  49812. this.value += 1;
  49813. }
  49814. return this;
  49815. };
  49816. // used by animation engine
  49817. PathCursor.prototype.raiseOnChange = function () {
  49818. var _this = this;
  49819. this._onchange.forEach(function (f) { return f(_this); });
  49820. return this;
  49821. };
  49822. PathCursor.prototype.onchange = function (f) {
  49823. this._onchange.push(f);
  49824. return this;
  49825. };
  49826. return PathCursor;
  49827. }());
  49828. BABYLON.PathCursor = PathCursor;
  49829. var AnimationKeyInterpolation;
  49830. (function (AnimationKeyInterpolation) {
  49831. /**
  49832. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49833. */
  49834. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49835. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49836. /**
  49837. * Class used to store any kind of animation
  49838. */
  49839. var Animation = /** @class */ (function () {
  49840. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49841. this.name = name;
  49842. this.targetProperty = targetProperty;
  49843. this.framePerSecond = framePerSecond;
  49844. this.dataType = dataType;
  49845. this.loopMode = loopMode;
  49846. this.enableBlending = enableBlending;
  49847. this._runtimeAnimations = new Array();
  49848. // The set of event that will be linked to this animation
  49849. this._events = new Array();
  49850. this.blendingSpeed = 0.01;
  49851. this._ranges = {};
  49852. this.targetPropertyPath = targetProperty.split(".");
  49853. this.dataType = dataType;
  49854. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49855. }
  49856. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49857. var dataType = undefined;
  49858. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49859. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49860. }
  49861. else if (from instanceof BABYLON.Quaternion) {
  49862. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49863. }
  49864. else if (from instanceof BABYLON.Vector3) {
  49865. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49866. }
  49867. else if (from instanceof BABYLON.Vector2) {
  49868. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49869. }
  49870. else if (from instanceof BABYLON.Color3) {
  49871. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49872. }
  49873. else if (from instanceof BABYLON.Size) {
  49874. dataType = Animation.ANIMATIONTYPE_SIZE;
  49875. }
  49876. if (dataType == undefined) {
  49877. return null;
  49878. }
  49879. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49880. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49881. animation.setKeys(keys);
  49882. if (easingFunction !== undefined) {
  49883. animation.setEasingFunction(easingFunction);
  49884. }
  49885. return animation;
  49886. };
  49887. /**
  49888. * Sets up an animation.
  49889. * @param property the property to animate
  49890. * @param animationType the animation type to apply
  49891. * @param easingFunction the easing function used in the animation
  49892. * @returns The created animation
  49893. */
  49894. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49895. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49896. animation.setEasingFunction(easingFunction);
  49897. return animation;
  49898. };
  49899. /**
  49900. * Create and start an animation on a node
  49901. * @param {string} name defines the name of the global animation that will be run on all nodes
  49902. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49903. * @param {string} targetProperty defines property to animate
  49904. * @param {number} framePerSecond defines the number of frame per second yo use
  49905. * @param {number} totalFrame defines the number of frames in total
  49906. * @param {any} from defines the initial value
  49907. * @param {any} to defines the final value
  49908. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49909. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49910. * @param onAnimationEnd defines the callback to call when animation end
  49911. * @returns the animatable created for this animation
  49912. */
  49913. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49914. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49915. if (!animation) {
  49916. return null;
  49917. }
  49918. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49919. };
  49920. /**
  49921. * Create and start an animation on a node and its descendants
  49922. * @param {string} name defines the name of the global animation that will be run on all nodes
  49923. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49924. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  49925. * @param {string} targetProperty defines property to animate
  49926. * @param {number} framePerSecond defines the number of frame per second yo use
  49927. * @param {number} totalFrame defines the number of frames in total
  49928. * @param {any} from defines the initial value
  49929. * @param {any} to defines the final value
  49930. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49931. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49932. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49933. * @returns the list of animatables created for all nodes
  49934. * @example https://www.babylonjs-playground.com/#MH0VLI
  49935. */
  49936. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49937. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49938. if (!animation) {
  49939. return null;
  49940. }
  49941. var scene = node.getScene();
  49942. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49943. };
  49944. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49945. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49946. if (!animation) {
  49947. return null;
  49948. }
  49949. node.animations.push(animation);
  49950. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49951. };
  49952. /**
  49953. * Transition property of the Camera to the target Value.
  49954. * @param property The property to transition
  49955. * @param targetValue The target Value of the property
  49956. * @param host The object where the property to animate belongs
  49957. * @param scene Scene used to run the animation
  49958. * @param frameRate Framerate (in frame/s) to use
  49959. * @param transition The transition type we want to use
  49960. * @param duration The duration of the animation, in milliseconds
  49961. * @param onAnimationEnd Call back trigger at the end of the animation.
  49962. */
  49963. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49964. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49965. if (duration <= 0) {
  49966. host[property] = targetValue;
  49967. if (onAnimationEnd) {
  49968. onAnimationEnd();
  49969. }
  49970. return null;
  49971. }
  49972. var endFrame = frameRate * (duration / 1000);
  49973. transition.setKeys([{
  49974. frame: 0,
  49975. value: host[property].clone ? host[property].clone() : host[property]
  49976. },
  49977. {
  49978. frame: endFrame,
  49979. value: targetValue
  49980. }]);
  49981. if (!host.animations) {
  49982. host.animations = [];
  49983. }
  49984. host.animations.push(transition);
  49985. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49986. animation.onAnimationEnd = onAnimationEnd;
  49987. return animation;
  49988. };
  49989. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49990. /**
  49991. * Return the array of runtime animations currently using this animation
  49992. */
  49993. get: function () {
  49994. return this._runtimeAnimations;
  49995. },
  49996. enumerable: true,
  49997. configurable: true
  49998. });
  49999. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50000. get: function () {
  50001. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50002. var runtimeAnimation = _a[_i];
  50003. if (!runtimeAnimation.isStopped) {
  50004. return true;
  50005. }
  50006. }
  50007. return false;
  50008. },
  50009. enumerable: true,
  50010. configurable: true
  50011. });
  50012. // Methods
  50013. /**
  50014. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  50015. */
  50016. Animation.prototype.toString = function (fullDetails) {
  50017. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50018. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50019. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50020. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50021. if (fullDetails) {
  50022. ret += ", Ranges: {";
  50023. var first = true;
  50024. for (var name in this._ranges) {
  50025. if (first) {
  50026. ret += ", ";
  50027. first = false;
  50028. }
  50029. ret += name;
  50030. }
  50031. ret += "}";
  50032. }
  50033. return ret;
  50034. };
  50035. /**
  50036. * Add an event to this animation.
  50037. */
  50038. Animation.prototype.addEvent = function (event) {
  50039. this._events.push(event);
  50040. };
  50041. /**
  50042. * Remove all events found at the given frame
  50043. * @param frame
  50044. */
  50045. Animation.prototype.removeEvents = function (frame) {
  50046. for (var index = 0; index < this._events.length; index++) {
  50047. if (this._events[index].frame === frame) {
  50048. this._events.splice(index, 1);
  50049. index--;
  50050. }
  50051. }
  50052. };
  50053. Animation.prototype.getEvents = function () {
  50054. return this._events;
  50055. };
  50056. Animation.prototype.createRange = function (name, from, to) {
  50057. // check name not already in use; could happen for bones after serialized
  50058. if (!this._ranges[name]) {
  50059. this._ranges[name] = new AnimationRange(name, from, to);
  50060. }
  50061. };
  50062. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50063. if (deleteFrames === void 0) { deleteFrames = true; }
  50064. var range = this._ranges[name];
  50065. if (!range) {
  50066. return;
  50067. }
  50068. if (deleteFrames) {
  50069. var from = range.from;
  50070. var to = range.to;
  50071. // this loop MUST go high to low for multiple splices to work
  50072. for (var key = this._keys.length - 1; key >= 0; key--) {
  50073. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50074. this._keys.splice(key, 1);
  50075. }
  50076. }
  50077. }
  50078. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50079. };
  50080. Animation.prototype.getRange = function (name) {
  50081. return this._ranges[name];
  50082. };
  50083. Animation.prototype.getKeys = function () {
  50084. return this._keys;
  50085. };
  50086. Animation.prototype.getHighestFrame = function () {
  50087. var ret = 0;
  50088. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50089. if (ret < this._keys[key].frame) {
  50090. ret = this._keys[key].frame;
  50091. }
  50092. }
  50093. return ret;
  50094. };
  50095. Animation.prototype.getEasingFunction = function () {
  50096. return this._easingFunction;
  50097. };
  50098. Animation.prototype.setEasingFunction = function (easingFunction) {
  50099. this._easingFunction = easingFunction;
  50100. };
  50101. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50102. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50103. };
  50104. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50105. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50106. };
  50107. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50108. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50109. };
  50110. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50111. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50112. };
  50113. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50114. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50115. };
  50116. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50117. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50118. };
  50119. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50120. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50121. };
  50122. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50123. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50124. };
  50125. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50126. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50127. };
  50128. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50129. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50130. };
  50131. /**
  50132. * Defines the function to use to interpolate matrices
  50133. * @param startValue defines the start matrix
  50134. * @param endValue defines the end matrix
  50135. * @param gradient defines the gradient between both matrices
  50136. * @param result defines an optional target matrix where to store the interpolation
  50137. * @returns the interpolated matrix
  50138. */
  50139. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50140. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50141. if (result) {
  50142. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50143. return result;
  50144. }
  50145. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50146. }
  50147. if (result) {
  50148. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50149. return result;
  50150. }
  50151. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50152. };
  50153. Animation.prototype.clone = function () {
  50154. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50155. clone.enableBlending = this.enableBlending;
  50156. clone.blendingSpeed = this.blendingSpeed;
  50157. if (this._keys) {
  50158. clone.setKeys(this._keys);
  50159. }
  50160. if (this._ranges) {
  50161. clone._ranges = {};
  50162. for (var name in this._ranges) {
  50163. var range = this._ranges[name];
  50164. if (!range) {
  50165. continue;
  50166. }
  50167. clone._ranges[name] = range.clone();
  50168. }
  50169. }
  50170. return clone;
  50171. };
  50172. Animation.prototype.setKeys = function (values) {
  50173. this._keys = values.slice(0);
  50174. };
  50175. Animation.prototype.serialize = function () {
  50176. var serializationObject = {};
  50177. serializationObject.name = this.name;
  50178. serializationObject.property = this.targetProperty;
  50179. serializationObject.framePerSecond = this.framePerSecond;
  50180. serializationObject.dataType = this.dataType;
  50181. serializationObject.loopBehavior = this.loopMode;
  50182. serializationObject.enableBlending = this.enableBlending;
  50183. serializationObject.blendingSpeed = this.blendingSpeed;
  50184. var dataType = this.dataType;
  50185. serializationObject.keys = [];
  50186. var keys = this.getKeys();
  50187. for (var index = 0; index < keys.length; index++) {
  50188. var animationKey = keys[index];
  50189. var key = {};
  50190. key.frame = animationKey.frame;
  50191. switch (dataType) {
  50192. case Animation.ANIMATIONTYPE_FLOAT:
  50193. key.values = [animationKey.value];
  50194. break;
  50195. case Animation.ANIMATIONTYPE_QUATERNION:
  50196. case Animation.ANIMATIONTYPE_MATRIX:
  50197. case Animation.ANIMATIONTYPE_VECTOR3:
  50198. case Animation.ANIMATIONTYPE_COLOR3:
  50199. key.values = animationKey.value.asArray();
  50200. break;
  50201. }
  50202. serializationObject.keys.push(key);
  50203. }
  50204. serializationObject.ranges = [];
  50205. for (var name in this._ranges) {
  50206. var source = this._ranges[name];
  50207. if (!source) {
  50208. continue;
  50209. }
  50210. var range = {};
  50211. range.name = name;
  50212. range.from = source.from;
  50213. range.to = source.to;
  50214. serializationObject.ranges.push(range);
  50215. }
  50216. return serializationObject;
  50217. };
  50218. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50219. get: function () {
  50220. return Animation._ANIMATIONTYPE_FLOAT;
  50221. },
  50222. enumerable: true,
  50223. configurable: true
  50224. });
  50225. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50226. get: function () {
  50227. return Animation._ANIMATIONTYPE_VECTOR3;
  50228. },
  50229. enumerable: true,
  50230. configurable: true
  50231. });
  50232. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50233. get: function () {
  50234. return Animation._ANIMATIONTYPE_VECTOR2;
  50235. },
  50236. enumerable: true,
  50237. configurable: true
  50238. });
  50239. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50240. get: function () {
  50241. return Animation._ANIMATIONTYPE_SIZE;
  50242. },
  50243. enumerable: true,
  50244. configurable: true
  50245. });
  50246. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50247. get: function () {
  50248. return Animation._ANIMATIONTYPE_QUATERNION;
  50249. },
  50250. enumerable: true,
  50251. configurable: true
  50252. });
  50253. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50254. get: function () {
  50255. return Animation._ANIMATIONTYPE_MATRIX;
  50256. },
  50257. enumerable: true,
  50258. configurable: true
  50259. });
  50260. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50261. get: function () {
  50262. return Animation._ANIMATIONTYPE_COLOR3;
  50263. },
  50264. enumerable: true,
  50265. configurable: true
  50266. });
  50267. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50268. get: function () {
  50269. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50270. },
  50271. enumerable: true,
  50272. configurable: true
  50273. });
  50274. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50275. get: function () {
  50276. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50277. },
  50278. enumerable: true,
  50279. configurable: true
  50280. });
  50281. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50282. get: function () {
  50283. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50284. },
  50285. enumerable: true,
  50286. configurable: true
  50287. });
  50288. Animation.Parse = function (parsedAnimation) {
  50289. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50290. var dataType = parsedAnimation.dataType;
  50291. var keys = [];
  50292. var data;
  50293. var index;
  50294. if (parsedAnimation.enableBlending) {
  50295. animation.enableBlending = parsedAnimation.enableBlending;
  50296. }
  50297. if (parsedAnimation.blendingSpeed) {
  50298. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50299. }
  50300. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50301. var key = parsedAnimation.keys[index];
  50302. var inTangent;
  50303. var outTangent;
  50304. switch (dataType) {
  50305. case Animation.ANIMATIONTYPE_FLOAT:
  50306. data = key.values[0];
  50307. if (key.values.length >= 1) {
  50308. inTangent = key.values[1];
  50309. }
  50310. if (key.values.length >= 2) {
  50311. outTangent = key.values[2];
  50312. }
  50313. break;
  50314. case Animation.ANIMATIONTYPE_QUATERNION:
  50315. data = BABYLON.Quaternion.FromArray(key.values);
  50316. if (key.values.length >= 8) {
  50317. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50318. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50319. inTangent = _inTangent;
  50320. }
  50321. }
  50322. if (key.values.length >= 12) {
  50323. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50324. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50325. outTangent = _outTangent;
  50326. }
  50327. }
  50328. break;
  50329. case Animation.ANIMATIONTYPE_MATRIX:
  50330. data = BABYLON.Matrix.FromArray(key.values);
  50331. break;
  50332. case Animation.ANIMATIONTYPE_COLOR3:
  50333. data = BABYLON.Color3.FromArray(key.values);
  50334. break;
  50335. case Animation.ANIMATIONTYPE_VECTOR3:
  50336. default:
  50337. data = BABYLON.Vector3.FromArray(key.values);
  50338. break;
  50339. }
  50340. var keyData = {};
  50341. keyData.frame = key.frame;
  50342. keyData.value = data;
  50343. if (inTangent != undefined) {
  50344. keyData.inTangent = inTangent;
  50345. }
  50346. if (outTangent != undefined) {
  50347. keyData.outTangent = outTangent;
  50348. }
  50349. keys.push(keyData);
  50350. }
  50351. animation.setKeys(keys);
  50352. if (parsedAnimation.ranges) {
  50353. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50354. data = parsedAnimation.ranges[index];
  50355. animation.createRange(data.name, data.from, data.to);
  50356. }
  50357. }
  50358. return animation;
  50359. };
  50360. Animation.AppendSerializedAnimations = function (source, destination) {
  50361. if (source.animations) {
  50362. destination.animations = [];
  50363. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50364. var animation = source.animations[animationIndex];
  50365. destination.animations.push(animation.serialize());
  50366. }
  50367. }
  50368. };
  50369. /**
  50370. * Use matrix interpolation instead of using direct key value when animating matrices
  50371. */
  50372. Animation.AllowMatricesInterpolation = false;
  50373. /**
  50374. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50375. */
  50376. Animation.AllowMatrixDecomposeForInterpolation = true;
  50377. // Statics
  50378. Animation._ANIMATIONTYPE_FLOAT = 0;
  50379. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50380. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50381. Animation._ANIMATIONTYPE_MATRIX = 3;
  50382. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50383. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50384. Animation._ANIMATIONTYPE_SIZE = 6;
  50385. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50386. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50387. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50388. return Animation;
  50389. }());
  50390. BABYLON.Animation = Animation;
  50391. })(BABYLON || (BABYLON = {}));
  50392. //# sourceMappingURL=babylon.animation.js.map
  50393. "use strict";
  50394. var BABYLON;
  50395. (function (BABYLON) {
  50396. /**
  50397. * This class defines the direct association between an animation and a target
  50398. */
  50399. var TargetedAnimation = /** @class */ (function () {
  50400. function TargetedAnimation() {
  50401. }
  50402. return TargetedAnimation;
  50403. }());
  50404. BABYLON.TargetedAnimation = TargetedAnimation;
  50405. /**
  50406. * Use this class to create coordinated animations on multiple targets
  50407. */
  50408. var AnimationGroup = /** @class */ (function () {
  50409. function AnimationGroup(name, scene) {
  50410. if (scene === void 0) { scene = null; }
  50411. this.name = name;
  50412. this._targetedAnimations = new Array();
  50413. this._animatables = new Array();
  50414. this._from = Number.MAX_VALUE;
  50415. this._to = -Number.MAX_VALUE;
  50416. this._speedRatio = 1;
  50417. this.onAnimationEndObservable = new BABYLON.Observable();
  50418. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50419. this._scene.animationGroups.push(this);
  50420. }
  50421. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50422. /**
  50423. * Define if the animations are started
  50424. */
  50425. get: function () {
  50426. return this._isStarted;
  50427. },
  50428. enumerable: true,
  50429. configurable: true
  50430. });
  50431. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50432. /**
  50433. * Gets or sets the speed ratio to use for all animations
  50434. */
  50435. get: function () {
  50436. return this._speedRatio;
  50437. },
  50438. /**
  50439. * Gets or sets the speed ratio to use for all animations
  50440. */
  50441. set: function (value) {
  50442. if (this._speedRatio === value) {
  50443. return;
  50444. }
  50445. this._speedRatio = value;
  50446. for (var index = 0; index < this._animatables.length; index++) {
  50447. var animatable = this._animatables[index];
  50448. animatable.speedRatio = this._speedRatio;
  50449. }
  50450. },
  50451. enumerable: true,
  50452. configurable: true
  50453. });
  50454. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50455. /**
  50456. * Gets the targeted animations for this animation group
  50457. */
  50458. get: function () {
  50459. return this._targetedAnimations;
  50460. },
  50461. enumerable: true,
  50462. configurable: true
  50463. });
  50464. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50465. /**
  50466. * returning the list of animatables controlled by this animation group.
  50467. */
  50468. get: function () {
  50469. return this._animatables;
  50470. },
  50471. enumerable: true,
  50472. configurable: true
  50473. });
  50474. /**
  50475. * Add an animation (with its target) in the group
  50476. * @param animation defines the animation we want to add
  50477. * @param target defines the target of the animation
  50478. * @returns the {BABYLON.TargetedAnimation} object
  50479. */
  50480. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50481. var targetedAnimation = {
  50482. animation: animation,
  50483. target: target
  50484. };
  50485. var keys = animation.getKeys();
  50486. if (this._from > keys[0].frame) {
  50487. this._from = keys[0].frame;
  50488. }
  50489. if (this._to < keys[keys.length - 1].frame) {
  50490. this._to = keys[keys.length - 1].frame;
  50491. }
  50492. this._targetedAnimations.push(targetedAnimation);
  50493. return targetedAnimation;
  50494. };
  50495. /**
  50496. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50497. * It can add constant keys at begin or end
  50498. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50499. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50500. */
  50501. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50502. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50503. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50504. beginFrame = Math.max(beginFrame, this._from);
  50505. endFrame = Math.min(endFrame, this._to);
  50506. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50507. var targetedAnimation = this._targetedAnimations[index];
  50508. var keys = targetedAnimation.animation.getKeys();
  50509. var startKey = keys[0];
  50510. var endKey = keys[keys.length - 1];
  50511. if (startKey.frame > beginFrame) {
  50512. var newKey = {
  50513. frame: beginFrame,
  50514. value: startKey.value,
  50515. inTangent: startKey.inTangent,
  50516. outTangent: startKey.outTangent,
  50517. interpolation: startKey.interpolation
  50518. };
  50519. keys.splice(0, 0, newKey);
  50520. }
  50521. if (endKey.frame < endFrame) {
  50522. var newKey = {
  50523. frame: endFrame,
  50524. value: endKey.value,
  50525. inTangent: endKey.outTangent,
  50526. outTangent: endKey.outTangent,
  50527. interpolation: endKey.interpolation
  50528. };
  50529. keys.push(newKey);
  50530. }
  50531. }
  50532. return this;
  50533. };
  50534. /**
  50535. * Start all animations on given targets
  50536. * @param loop defines if animations must loop
  50537. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50538. * @param from defines the from key (optional)
  50539. * @param to defines the to key (optional)
  50540. * @returns the current animation group
  50541. */
  50542. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50543. var _this = this;
  50544. if (loop === void 0) { loop = false; }
  50545. if (speedRatio === void 0) { speedRatio = 1; }
  50546. if (this._isStarted || this._targetedAnimations.length === 0) {
  50547. return this;
  50548. }
  50549. var _loop_1 = function () {
  50550. var targetedAnimation = this_1._targetedAnimations[index];
  50551. if (!targetedAnimation.target.animations) {
  50552. targetedAnimation.target.animations = [];
  50553. }
  50554. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  50555. targetedAnimation.target.animations.push(targetedAnimation.animation);
  50556. }
  50557. 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 () {
  50558. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50559. }));
  50560. };
  50561. var this_1 = this;
  50562. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50563. _loop_1();
  50564. }
  50565. this._speedRatio = speedRatio;
  50566. this._isStarted = true;
  50567. return this;
  50568. };
  50569. /**
  50570. * Pause all animations
  50571. */
  50572. AnimationGroup.prototype.pause = function () {
  50573. if (!this._isStarted) {
  50574. return this;
  50575. }
  50576. for (var index = 0; index < this._animatables.length; index++) {
  50577. var animatable = this._animatables[index];
  50578. animatable.pause();
  50579. }
  50580. return this;
  50581. };
  50582. /**
  50583. * Play all animations to initial state
  50584. * This function will start() the animations if they were not started or will restart() them if they were paused
  50585. * @param loop defines if animations must loop
  50586. */
  50587. AnimationGroup.prototype.play = function (loop) {
  50588. if (this.isStarted) {
  50589. if (loop !== undefined) {
  50590. for (var index = 0; index < this._animatables.length; index++) {
  50591. var animatable = this._animatables[index];
  50592. animatable.loopAnimation = loop;
  50593. }
  50594. }
  50595. this.restart();
  50596. }
  50597. else {
  50598. this.start(loop, this._speedRatio);
  50599. }
  50600. return this;
  50601. };
  50602. /**
  50603. * Reset all animations to initial state
  50604. */
  50605. AnimationGroup.prototype.reset = function () {
  50606. if (!this._isStarted) {
  50607. return this;
  50608. }
  50609. for (var index = 0; index < this._animatables.length; index++) {
  50610. var animatable = this._animatables[index];
  50611. animatable.reset();
  50612. }
  50613. return this;
  50614. };
  50615. /**
  50616. * Restart animations from key 0
  50617. */
  50618. AnimationGroup.prototype.restart = function () {
  50619. if (!this._isStarted) {
  50620. return this;
  50621. }
  50622. for (var index = 0; index < this._animatables.length; index++) {
  50623. var animatable = this._animatables[index];
  50624. animatable.restart();
  50625. }
  50626. return this;
  50627. };
  50628. /**
  50629. * Stop all animations
  50630. */
  50631. AnimationGroup.prototype.stop = function () {
  50632. if (!this._isStarted) {
  50633. return this;
  50634. }
  50635. for (var index = 0; index < this._animatables.length; index++) {
  50636. var animatable = this._animatables[index];
  50637. animatable.stop();
  50638. }
  50639. this._isStarted = false;
  50640. return this;
  50641. };
  50642. /**
  50643. * Goes to a specific frame in this animation group
  50644. *
  50645. * @param frame the frame number to go to
  50646. * @return the animationGroup
  50647. */
  50648. AnimationGroup.prototype.goToFrame = function (frame) {
  50649. if (!this._isStarted) {
  50650. return this;
  50651. }
  50652. for (var index = 0; index < this._animatables.length; index++) {
  50653. var animatable = this._animatables[index];
  50654. animatable.goToFrame(frame);
  50655. }
  50656. return this;
  50657. };
  50658. /**
  50659. * Dispose all associated resources
  50660. */
  50661. AnimationGroup.prototype.dispose = function () {
  50662. this._targetedAnimations = [];
  50663. this._animatables = [];
  50664. var index = this._scene.animationGroups.indexOf(this);
  50665. if (index > -1) {
  50666. this._scene.animationGroups.splice(index, 1);
  50667. }
  50668. };
  50669. return AnimationGroup;
  50670. }());
  50671. BABYLON.AnimationGroup = AnimationGroup;
  50672. })(BABYLON || (BABYLON = {}));
  50673. //# sourceMappingURL=babylon.animationGroup.js.map
  50674. "use strict";
  50675. var BABYLON;
  50676. (function (BABYLON) {
  50677. var RuntimeAnimation = /** @class */ (function () {
  50678. /**
  50679. * Create a new RuntimeAnimation object
  50680. * @param target defines the target of the animation
  50681. * @param animation defines the source {BABYLON.Animation} object
  50682. * @param scene defines the hosting scene
  50683. * @param host defines the initiating Animatable
  50684. */
  50685. function RuntimeAnimation(target, animation, scene, host) {
  50686. this._currentFrame = 0;
  50687. this._offsetsCache = {};
  50688. this._highLimitsCache = {};
  50689. this._stopped = false;
  50690. this._blendingFactor = 0;
  50691. this._targetPath = "";
  50692. this._weight = 1.0;
  50693. this._ratioOffset = 0;
  50694. this._previousDelay = 0;
  50695. this._previousRatio = 0;
  50696. this._animation = animation;
  50697. this._target = target;
  50698. this._scene = scene;
  50699. this._host = host;
  50700. animation._runtimeAnimations.push(this);
  50701. }
  50702. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50703. /**
  50704. * Gets the current frame
  50705. */
  50706. get: function () {
  50707. return this._currentFrame;
  50708. },
  50709. enumerable: true,
  50710. configurable: true
  50711. });
  50712. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50713. /**
  50714. * Gets the weight of the runtime animation
  50715. */
  50716. get: function () {
  50717. return this._weight;
  50718. },
  50719. enumerable: true,
  50720. configurable: true
  50721. });
  50722. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  50723. /**
  50724. * Gets the original value of the runtime animation
  50725. */
  50726. get: function () {
  50727. return this._originalValue;
  50728. },
  50729. enumerable: true,
  50730. configurable: true
  50731. });
  50732. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50733. /**
  50734. * Gets the current value of the runtime animation
  50735. */
  50736. get: function () {
  50737. return this._currentValue;
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50743. /**
  50744. * Gets the path where to store the animated value in the target
  50745. */
  50746. get: function () {
  50747. return this._targetPath;
  50748. },
  50749. enumerable: true,
  50750. configurable: true
  50751. });
  50752. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50753. /**
  50754. * Gets the actual target of the runtime animation
  50755. */
  50756. get: function () {
  50757. return this._activeTarget;
  50758. },
  50759. enumerable: true,
  50760. configurable: true
  50761. });
  50762. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50763. get: function () {
  50764. return this._animation;
  50765. },
  50766. enumerable: true,
  50767. configurable: true
  50768. });
  50769. RuntimeAnimation.prototype.reset = function () {
  50770. this._offsetsCache = {};
  50771. this._highLimitsCache = {};
  50772. this._currentFrame = 0;
  50773. this._blendingFactor = 0;
  50774. this._originalValue = null;
  50775. };
  50776. RuntimeAnimation.prototype.isStopped = function () {
  50777. return this._stopped;
  50778. };
  50779. RuntimeAnimation.prototype.dispose = function () {
  50780. var index = this._animation.runtimeAnimations.indexOf(this);
  50781. if (index > -1) {
  50782. this._animation.runtimeAnimations.splice(index, 1);
  50783. }
  50784. };
  50785. RuntimeAnimation.prototype._getKeyValue = function (value) {
  50786. if (typeof value === "function") {
  50787. return value();
  50788. }
  50789. return value;
  50790. };
  50791. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50792. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50793. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50794. }
  50795. this._currentFrame = currentFrame;
  50796. var keys = this._animation.getKeys();
  50797. // Try to get a hash to find the right key
  50798. 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));
  50799. if (keys[startKeyIndex].frame >= currentFrame) {
  50800. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50801. startKeyIndex--;
  50802. }
  50803. }
  50804. for (var key = startKeyIndex; key < keys.length; key++) {
  50805. var endKey = keys[key + 1];
  50806. if (endKey.frame >= currentFrame) {
  50807. var startKey = keys[key];
  50808. var startValue = this._getKeyValue(startKey.value);
  50809. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  50810. return startValue;
  50811. }
  50812. var endValue = this._getKeyValue(endKey.value);
  50813. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50814. var frameDelta = endKey.frame - startKey.frame;
  50815. // gradient : percent of currentFrame between the frame inf and the frame sup
  50816. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50817. // check for easingFunction and correction of gradient
  50818. var easingFunction = this._animation.getEasingFunction();
  50819. if (easingFunction != null) {
  50820. gradient = easingFunction.ease(gradient);
  50821. }
  50822. switch (this._animation.dataType) {
  50823. // Float
  50824. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50825. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  50826. switch (loopMode) {
  50827. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50828. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50829. return floatValue;
  50830. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50831. return offsetValue * repeatCount + floatValue;
  50832. }
  50833. break;
  50834. // Quaternion
  50835. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50836. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  50837. switch (loopMode) {
  50838. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50839. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50840. return quatValue;
  50841. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50842. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50843. }
  50844. return quatValue;
  50845. // Vector3
  50846. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50847. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50848. switch (loopMode) {
  50849. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50850. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50851. return vec3Value;
  50852. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50853. return vec3Value.add(offsetValue.scale(repeatCount));
  50854. }
  50855. // Vector2
  50856. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50857. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50858. switch (loopMode) {
  50859. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50860. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50861. return vec2Value;
  50862. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50863. return vec2Value.add(offsetValue.scale(repeatCount));
  50864. }
  50865. // Size
  50866. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50867. switch (loopMode) {
  50868. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50869. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50870. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50871. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50872. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50873. }
  50874. // Color3
  50875. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50876. switch (loopMode) {
  50877. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50878. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50879. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50880. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50881. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50882. }
  50883. // Matrix
  50884. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50885. switch (loopMode) {
  50886. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50887. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50888. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50889. this._workValue = this._animation.matrixInterpolateFunction(startValue, endValue, gradient, this._workValue);
  50890. return this._workValue;
  50891. }
  50892. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50893. return startValue;
  50894. }
  50895. default:
  50896. break;
  50897. }
  50898. break;
  50899. }
  50900. }
  50901. return this._getKeyValue(keys[keys.length - 1].value);
  50902. };
  50903. /**
  50904. * Affect the interpolated value to the target
  50905. * @param currentValue defines the value computed by the animation
  50906. * @param weight defines the weight to apply to this value
  50907. */
  50908. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50909. if (weight === void 0) { weight = 1.0; }
  50910. if (this._target instanceof Array) {
  50911. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50912. var target = _a[_i];
  50913. this._setValue(target, currentValue, weight);
  50914. }
  50915. }
  50916. else {
  50917. this._setValue(this._target, currentValue, weight);
  50918. }
  50919. };
  50920. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  50921. if (weight === void 0) { weight = 1.0; }
  50922. // Set value
  50923. var path;
  50924. var destination;
  50925. var targetPropertyPath = this._animation.targetPropertyPath;
  50926. if (targetPropertyPath.length > 1) {
  50927. var property = target[targetPropertyPath[0]];
  50928. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50929. property = property[targetPropertyPath[index]];
  50930. }
  50931. path = targetPropertyPath[targetPropertyPath.length - 1];
  50932. destination = property;
  50933. }
  50934. else {
  50935. path = targetPropertyPath[0];
  50936. destination = target;
  50937. }
  50938. this._targetPath = path;
  50939. this._activeTarget = destination;
  50940. this._weight = weight;
  50941. // Blending
  50942. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50943. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50944. if (enableBlending && this._blendingFactor <= 1.0) {
  50945. if (!this._originalBlendValue) {
  50946. var originalValue = destination[path];
  50947. if (originalValue.clone) {
  50948. this._originalBlendValue = originalValue.clone();
  50949. }
  50950. else {
  50951. this._originalBlendValue = originalValue;
  50952. }
  50953. }
  50954. }
  50955. if (weight !== -1.0) {
  50956. if (!this._originalValue) {
  50957. var originalValue = void 0;
  50958. if (destination.getRestPose) {
  50959. originalValue = destination.getRestPose();
  50960. }
  50961. else {
  50962. originalValue = destination[path];
  50963. }
  50964. if (originalValue.clone) {
  50965. this._originalValue = originalValue.clone();
  50966. }
  50967. else {
  50968. this._originalValue = originalValue;
  50969. }
  50970. }
  50971. }
  50972. if (enableBlending && this._blendingFactor <= 1.0) {
  50973. if (this._originalBlendValue.prototype) {
  50974. if (this._originalBlendValue.prototype.Lerp) {
  50975. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50976. }
  50977. else {
  50978. this._currentValue = currentValue;
  50979. }
  50980. }
  50981. else if (this._originalBlendValue.m) {
  50982. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50983. if (this._currentValue) {
  50984. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50985. }
  50986. else {
  50987. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50988. }
  50989. }
  50990. else {
  50991. if (this._currentValue) {
  50992. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50993. }
  50994. else {
  50995. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50996. }
  50997. }
  50998. }
  50999. else {
  51000. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51001. }
  51002. this._blendingFactor += blendingSpeed;
  51003. }
  51004. else {
  51005. this._currentValue = currentValue;
  51006. }
  51007. if (weight !== -1.0) {
  51008. this._scene._registerTargetForLateAnimationBinding(this);
  51009. }
  51010. else {
  51011. destination[path] = this._currentValue;
  51012. }
  51013. if (target.markAsDirty) {
  51014. target.markAsDirty(this._animation.targetProperty);
  51015. }
  51016. };
  51017. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51018. if (this._target && this._target.animationPropertiesOverride) {
  51019. return this._target.animationPropertiesOverride.loopMode;
  51020. }
  51021. return this._animation.loopMode;
  51022. };
  51023. /**
  51024. * Move the current animation to a given frame
  51025. * @param frame defines the frame to move to
  51026. */
  51027. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51028. var keys = this._animation.getKeys();
  51029. if (frame < keys[0].frame) {
  51030. frame = keys[0].frame;
  51031. }
  51032. else if (frame > keys[keys.length - 1].frame) {
  51033. frame = keys[keys.length - 1].frame;
  51034. }
  51035. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51036. this.setValue(currentValue, -1);
  51037. };
  51038. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51039. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51040. this._ratioOffset = this._previousRatio - newRatio;
  51041. };
  51042. /**
  51043. * Execute the current animation
  51044. * @param delay defines the delay to add to the current frame
  51045. * @param from defines the lower bound of the animation range
  51046. * @param to defines the upper bound of the animation range
  51047. * @param loop defines if the current animation must loop
  51048. * @param speedRatio defines the current speed ratio
  51049. * @param weight defines the weight of the animation (default is -1 so no weight)
  51050. * @returns a boolean indicating if the animation has ended
  51051. */
  51052. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51053. if (weight === void 0) { weight = -1.0; }
  51054. var targetPropertyPath = this._animation.targetPropertyPath;
  51055. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51056. this._stopped = true;
  51057. return false;
  51058. }
  51059. var returnValue = true;
  51060. var keys = this._animation.getKeys();
  51061. // Adding a start key at frame 0 if missing
  51062. if (keys[0].frame !== 0) {
  51063. var newKey = { frame: 0, value: keys[0].value };
  51064. keys.splice(0, 0, newKey);
  51065. }
  51066. // Check limits
  51067. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51068. from = keys[0].frame;
  51069. }
  51070. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51071. to = keys[keys.length - 1].frame;
  51072. }
  51073. //to and from cannot be the same key
  51074. if (from === to) {
  51075. if (from > keys[0].frame) {
  51076. from--;
  51077. }
  51078. else if (to < keys[keys.length - 1].frame) {
  51079. to++;
  51080. }
  51081. }
  51082. // Compute ratio
  51083. var range = to - from;
  51084. var offsetValue;
  51085. // ratio represents the frame delta between from and to
  51086. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51087. var highLimitValue = 0;
  51088. this._previousDelay = delay;
  51089. this._previousRatio = ratio;
  51090. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  51091. returnValue = false;
  51092. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  51093. }
  51094. else {
  51095. // Get max value if required
  51096. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51097. var keyOffset = to.toString() + from.toString();
  51098. if (!this._offsetsCache[keyOffset]) {
  51099. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51100. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51101. switch (this._animation.dataType) {
  51102. // Float
  51103. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51104. this._offsetsCache[keyOffset] = toValue - fromValue;
  51105. break;
  51106. // Quaternion
  51107. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51108. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51109. break;
  51110. // Vector3
  51111. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51112. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51113. // Vector2
  51114. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51115. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51116. // Size
  51117. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51118. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51119. // Color3
  51120. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51121. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51122. default:
  51123. break;
  51124. }
  51125. this._highLimitsCache[keyOffset] = toValue;
  51126. }
  51127. highLimitValue = this._highLimitsCache[keyOffset];
  51128. offsetValue = this._offsetsCache[keyOffset];
  51129. }
  51130. }
  51131. if (offsetValue === undefined) {
  51132. switch (this._animation.dataType) {
  51133. // Float
  51134. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51135. offsetValue = 0;
  51136. break;
  51137. // Quaternion
  51138. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51139. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51140. break;
  51141. // Vector3
  51142. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51143. offsetValue = BABYLON.Vector3.Zero();
  51144. break;
  51145. // Vector2
  51146. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51147. offsetValue = BABYLON.Vector2.Zero();
  51148. break;
  51149. // Size
  51150. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51151. offsetValue = BABYLON.Size.Zero();
  51152. break;
  51153. // Color3
  51154. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51155. offsetValue = BABYLON.Color3.Black();
  51156. }
  51157. }
  51158. // Compute value
  51159. var repeatCount = (ratio / range) >> 0;
  51160. var currentFrame = returnValue ? from + ratio % range : to;
  51161. // Need to normalize?
  51162. if (this._host && this._host.syncRoot) {
  51163. var syncRoot = this._host.syncRoot;
  51164. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51165. currentFrame = from + (to - from) * hostNormalizedFrame;
  51166. }
  51167. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51168. // Set value
  51169. this.setValue(currentValue, weight);
  51170. // Check events
  51171. var events = this._animation.getEvents();
  51172. for (var index = 0; index < events.length; index++) {
  51173. // Make sure current frame has passed event frame and that event frame is within the current range
  51174. // Also, handle both forward and reverse animations
  51175. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51176. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51177. var event = events[index];
  51178. if (!event.isDone) {
  51179. // If event should be done only once, remove it.
  51180. if (event.onlyOnce) {
  51181. events.splice(index, 1);
  51182. index--;
  51183. }
  51184. event.isDone = true;
  51185. event.action();
  51186. } // Don't do anything if the event has already be done.
  51187. }
  51188. else if (events[index].isDone && !events[index].onlyOnce) {
  51189. // reset event, the animation is looping
  51190. events[index].isDone = false;
  51191. }
  51192. }
  51193. if (!returnValue) {
  51194. this._stopped = true;
  51195. }
  51196. return returnValue;
  51197. };
  51198. return RuntimeAnimation;
  51199. }());
  51200. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51201. })(BABYLON || (BABYLON = {}));
  51202. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51203. "use strict";
  51204. var BABYLON;
  51205. (function (BABYLON) {
  51206. var Animatable = /** @class */ (function () {
  51207. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51208. if (fromFrame === void 0) { fromFrame = 0; }
  51209. if (toFrame === void 0) { toFrame = 100; }
  51210. if (loopAnimation === void 0) { loopAnimation = false; }
  51211. if (speedRatio === void 0) { speedRatio = 1.0; }
  51212. this.target = target;
  51213. this.fromFrame = fromFrame;
  51214. this.toFrame = toFrame;
  51215. this.loopAnimation = loopAnimation;
  51216. this.onAnimationEnd = onAnimationEnd;
  51217. this._localDelayOffset = null;
  51218. this._pausedDelay = null;
  51219. this._runtimeAnimations = new Array();
  51220. this._paused = false;
  51221. this._speedRatio = 1;
  51222. this._weight = -1.0;
  51223. this.animationStarted = false;
  51224. this._scene = scene;
  51225. if (animations) {
  51226. this.appendAnimations(target, animations);
  51227. }
  51228. this._speedRatio = speedRatio;
  51229. scene._activeAnimatables.push(this);
  51230. }
  51231. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51232. /**
  51233. * Gets the root Animatable used to synchronize and normalize animations
  51234. */
  51235. get: function () {
  51236. return this._syncRoot;
  51237. },
  51238. enumerable: true,
  51239. configurable: true
  51240. });
  51241. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51242. /**
  51243. * Gets the current frame of the first RuntimeAnimation
  51244. * Used to synchronize Animatables
  51245. */
  51246. get: function () {
  51247. if (this._runtimeAnimations.length === 0) {
  51248. return 0;
  51249. }
  51250. return this._runtimeAnimations[0].currentFrame;
  51251. },
  51252. enumerable: true,
  51253. configurable: true
  51254. });
  51255. Object.defineProperty(Animatable.prototype, "weight", {
  51256. /**
  51257. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51258. */
  51259. get: function () {
  51260. return this._weight;
  51261. },
  51262. set: function (value) {
  51263. if (value === -1) {
  51264. this._weight = -1;
  51265. return;
  51266. }
  51267. // Else weight must be in [0, 1] range
  51268. this._weight = Math.min(Math.max(value, 0), 1.0);
  51269. },
  51270. enumerable: true,
  51271. configurable: true
  51272. });
  51273. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51274. /**
  51275. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51276. */
  51277. get: function () {
  51278. return this._speedRatio;
  51279. },
  51280. set: function (value) {
  51281. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51282. var animation = this._runtimeAnimations[index];
  51283. animation._prepareForSpeedRatioChange(value);
  51284. }
  51285. this._speedRatio = value;
  51286. },
  51287. enumerable: true,
  51288. configurable: true
  51289. });
  51290. // Methods
  51291. /**
  51292. * Synchronize and normalize current Animatable with a source Animatable.
  51293. * This is useful when using animation weights and when animations are not of the same length
  51294. * @param root defines the root Animatable to synchronize with
  51295. * @returns the current Animatable
  51296. */
  51297. Animatable.prototype.syncWith = function (root) {
  51298. this._syncRoot = root;
  51299. if (root) {
  51300. // Make sure this animatable will animate after the root
  51301. var index = this._scene._activeAnimatables.indexOf(this);
  51302. if (index > -1) {
  51303. this._scene._activeAnimatables.splice(index, 1);
  51304. this._scene._activeAnimatables.push(this);
  51305. }
  51306. }
  51307. return this;
  51308. };
  51309. Animatable.prototype.getAnimations = function () {
  51310. return this._runtimeAnimations;
  51311. };
  51312. Animatable.prototype.appendAnimations = function (target, animations) {
  51313. for (var index = 0; index < animations.length; index++) {
  51314. var animation = animations[index];
  51315. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51316. }
  51317. };
  51318. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51319. var runtimeAnimations = this._runtimeAnimations;
  51320. for (var index = 0; index < runtimeAnimations.length; index++) {
  51321. if (runtimeAnimations[index].animation.targetProperty === property) {
  51322. return runtimeAnimations[index].animation;
  51323. }
  51324. }
  51325. return null;
  51326. };
  51327. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51328. var runtimeAnimations = this._runtimeAnimations;
  51329. for (var index = 0; index < runtimeAnimations.length; index++) {
  51330. if (runtimeAnimations[index].animation.targetProperty === property) {
  51331. return runtimeAnimations[index];
  51332. }
  51333. }
  51334. return null;
  51335. };
  51336. Animatable.prototype.reset = function () {
  51337. var runtimeAnimations = this._runtimeAnimations;
  51338. for (var index = 0; index < runtimeAnimations.length; index++) {
  51339. runtimeAnimations[index].reset();
  51340. }
  51341. // Reset to original value
  51342. for (index = 0; index < runtimeAnimations.length; index++) {
  51343. var animation = runtimeAnimations[index];
  51344. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51345. }
  51346. this._localDelayOffset = null;
  51347. this._pausedDelay = null;
  51348. };
  51349. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51350. var runtimeAnimations = this._runtimeAnimations;
  51351. for (var index = 0; index < runtimeAnimations.length; index++) {
  51352. runtimeAnimations[index].animation.enableBlending = true;
  51353. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51354. }
  51355. };
  51356. Animatable.prototype.disableBlending = function () {
  51357. var runtimeAnimations = this._runtimeAnimations;
  51358. for (var index = 0; index < runtimeAnimations.length; index++) {
  51359. runtimeAnimations[index].animation.enableBlending = false;
  51360. }
  51361. };
  51362. Animatable.prototype.goToFrame = function (frame) {
  51363. var runtimeAnimations = this._runtimeAnimations;
  51364. if (runtimeAnimations[0]) {
  51365. var fps = runtimeAnimations[0].animation.framePerSecond;
  51366. var currentFrame = runtimeAnimations[0].currentFrame;
  51367. var adjustTime = frame - currentFrame;
  51368. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51369. if (this._localDelayOffset === null) {
  51370. this._localDelayOffset = 0;
  51371. }
  51372. this._localDelayOffset -= delay;
  51373. }
  51374. for (var index = 0; index < runtimeAnimations.length; index++) {
  51375. runtimeAnimations[index].goToFrame(frame);
  51376. }
  51377. };
  51378. Animatable.prototype.pause = function () {
  51379. if (this._paused) {
  51380. return;
  51381. }
  51382. this._paused = true;
  51383. };
  51384. Animatable.prototype.restart = function () {
  51385. this._paused = false;
  51386. };
  51387. Animatable.prototype.stop = function (animationName) {
  51388. if (animationName) {
  51389. var idx = this._scene._activeAnimatables.indexOf(this);
  51390. if (idx > -1) {
  51391. var runtimeAnimations = this._runtimeAnimations;
  51392. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51393. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51394. continue;
  51395. }
  51396. runtimeAnimations[index].dispose();
  51397. runtimeAnimations.splice(index, 1);
  51398. }
  51399. if (runtimeAnimations.length == 0) {
  51400. this._scene._activeAnimatables.splice(idx, 1);
  51401. if (this.onAnimationEnd) {
  51402. this.onAnimationEnd();
  51403. }
  51404. }
  51405. }
  51406. }
  51407. else {
  51408. var index = this._scene._activeAnimatables.indexOf(this);
  51409. if (index > -1) {
  51410. this._scene._activeAnimatables.splice(index, 1);
  51411. var runtimeAnimations = this._runtimeAnimations;
  51412. for (var index = 0; index < runtimeAnimations.length; index++) {
  51413. runtimeAnimations[index].dispose();
  51414. }
  51415. if (this.onAnimationEnd) {
  51416. this.onAnimationEnd();
  51417. }
  51418. }
  51419. }
  51420. };
  51421. Animatable.prototype._animate = function (delay) {
  51422. if (this._paused) {
  51423. this.animationStarted = false;
  51424. if (this._pausedDelay === null) {
  51425. this._pausedDelay = delay;
  51426. }
  51427. return true;
  51428. }
  51429. if (this._localDelayOffset === null) {
  51430. this._localDelayOffset = delay;
  51431. this._pausedDelay = null;
  51432. }
  51433. else if (this._pausedDelay !== null) {
  51434. this._localDelayOffset += delay - this._pausedDelay;
  51435. this._pausedDelay = null;
  51436. }
  51437. if (this._weight === 0) {
  51438. return true;
  51439. }
  51440. // Animating
  51441. var running = false;
  51442. var runtimeAnimations = this._runtimeAnimations;
  51443. var index;
  51444. for (index = 0; index < runtimeAnimations.length; index++) {
  51445. var animation = runtimeAnimations[index];
  51446. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51447. running = running || isRunning;
  51448. }
  51449. this.animationStarted = running;
  51450. if (!running) {
  51451. // Remove from active animatables
  51452. index = this._scene._activeAnimatables.indexOf(this);
  51453. this._scene._activeAnimatables.splice(index, 1);
  51454. // Dispose all runtime animations
  51455. for (index = 0; index < runtimeAnimations.length; index++) {
  51456. runtimeAnimations[index].dispose();
  51457. }
  51458. }
  51459. if (!running && this.onAnimationEnd) {
  51460. this.onAnimationEnd();
  51461. this.onAnimationEnd = null;
  51462. }
  51463. return running;
  51464. };
  51465. return Animatable;
  51466. }());
  51467. BABYLON.Animatable = Animatable;
  51468. })(BABYLON || (BABYLON = {}));
  51469. //# sourceMappingURL=babylon.animatable.js.map
  51470. "use strict";
  51471. var BABYLON;
  51472. (function (BABYLON) {
  51473. var EasingFunction = /** @class */ (function () {
  51474. function EasingFunction() {
  51475. // Properties
  51476. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51477. }
  51478. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51479. get: function () {
  51480. return EasingFunction._EASINGMODE_EASEIN;
  51481. },
  51482. enumerable: true,
  51483. configurable: true
  51484. });
  51485. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51486. get: function () {
  51487. return EasingFunction._EASINGMODE_EASEOUT;
  51488. },
  51489. enumerable: true,
  51490. configurable: true
  51491. });
  51492. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51493. get: function () {
  51494. return EasingFunction._EASINGMODE_EASEINOUT;
  51495. },
  51496. enumerable: true,
  51497. configurable: true
  51498. });
  51499. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51500. var n = Math.min(Math.max(easingMode, 0), 2);
  51501. this._easingMode = n;
  51502. };
  51503. EasingFunction.prototype.getEasingMode = function () {
  51504. return this._easingMode;
  51505. };
  51506. EasingFunction.prototype.easeInCore = function (gradient) {
  51507. throw new Error('You must implement this method');
  51508. };
  51509. EasingFunction.prototype.ease = function (gradient) {
  51510. switch (this._easingMode) {
  51511. case EasingFunction.EASINGMODE_EASEIN:
  51512. return this.easeInCore(gradient);
  51513. case EasingFunction.EASINGMODE_EASEOUT:
  51514. return (1 - this.easeInCore(1 - gradient));
  51515. }
  51516. if (gradient >= 0.5) {
  51517. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51518. }
  51519. return (this.easeInCore(gradient * 2) * 0.5);
  51520. };
  51521. //Statics
  51522. EasingFunction._EASINGMODE_EASEIN = 0;
  51523. EasingFunction._EASINGMODE_EASEOUT = 1;
  51524. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51525. return EasingFunction;
  51526. }());
  51527. BABYLON.EasingFunction = EasingFunction;
  51528. var CircleEase = /** @class */ (function (_super) {
  51529. __extends(CircleEase, _super);
  51530. function CircleEase() {
  51531. return _super !== null && _super.apply(this, arguments) || this;
  51532. }
  51533. CircleEase.prototype.easeInCore = function (gradient) {
  51534. gradient = Math.max(0, Math.min(1, gradient));
  51535. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51536. };
  51537. return CircleEase;
  51538. }(EasingFunction));
  51539. BABYLON.CircleEase = CircleEase;
  51540. var BackEase = /** @class */ (function (_super) {
  51541. __extends(BackEase, _super);
  51542. function BackEase(amplitude) {
  51543. if (amplitude === void 0) { amplitude = 1; }
  51544. var _this = _super.call(this) || this;
  51545. _this.amplitude = amplitude;
  51546. return _this;
  51547. }
  51548. BackEase.prototype.easeInCore = function (gradient) {
  51549. var num = Math.max(0, this.amplitude);
  51550. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51551. };
  51552. return BackEase;
  51553. }(EasingFunction));
  51554. BABYLON.BackEase = BackEase;
  51555. var BounceEase = /** @class */ (function (_super) {
  51556. __extends(BounceEase, _super);
  51557. function BounceEase(bounces, bounciness) {
  51558. if (bounces === void 0) { bounces = 3; }
  51559. if (bounciness === void 0) { bounciness = 2; }
  51560. var _this = _super.call(this) || this;
  51561. _this.bounces = bounces;
  51562. _this.bounciness = bounciness;
  51563. return _this;
  51564. }
  51565. BounceEase.prototype.easeInCore = function (gradient) {
  51566. var y = Math.max(0.0, this.bounces);
  51567. var bounciness = this.bounciness;
  51568. if (bounciness <= 1.0) {
  51569. bounciness = 1.001;
  51570. }
  51571. var num9 = Math.pow(bounciness, y);
  51572. var num5 = 1.0 - bounciness;
  51573. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51574. var num15 = gradient * num4;
  51575. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51576. var num3 = Math.floor(num65);
  51577. var num13 = num3 + 1.0;
  51578. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51579. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51580. var num7 = (num8 + num12) * 0.5;
  51581. var num6 = gradient - num7;
  51582. var num2 = num7 - num8;
  51583. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51584. };
  51585. return BounceEase;
  51586. }(EasingFunction));
  51587. BABYLON.BounceEase = BounceEase;
  51588. var CubicEase = /** @class */ (function (_super) {
  51589. __extends(CubicEase, _super);
  51590. function CubicEase() {
  51591. return _super !== null && _super.apply(this, arguments) || this;
  51592. }
  51593. CubicEase.prototype.easeInCore = function (gradient) {
  51594. return (gradient * gradient * gradient);
  51595. };
  51596. return CubicEase;
  51597. }(EasingFunction));
  51598. BABYLON.CubicEase = CubicEase;
  51599. var ElasticEase = /** @class */ (function (_super) {
  51600. __extends(ElasticEase, _super);
  51601. function ElasticEase(oscillations, springiness) {
  51602. if (oscillations === void 0) { oscillations = 3; }
  51603. if (springiness === void 0) { springiness = 3; }
  51604. var _this = _super.call(this) || this;
  51605. _this.oscillations = oscillations;
  51606. _this.springiness = springiness;
  51607. return _this;
  51608. }
  51609. ElasticEase.prototype.easeInCore = function (gradient) {
  51610. var num2;
  51611. var num3 = Math.max(0.0, this.oscillations);
  51612. var num = Math.max(0.0, this.springiness);
  51613. if (num == 0) {
  51614. num2 = gradient;
  51615. }
  51616. else {
  51617. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51618. }
  51619. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51620. };
  51621. return ElasticEase;
  51622. }(EasingFunction));
  51623. BABYLON.ElasticEase = ElasticEase;
  51624. var ExponentialEase = /** @class */ (function (_super) {
  51625. __extends(ExponentialEase, _super);
  51626. function ExponentialEase(exponent) {
  51627. if (exponent === void 0) { exponent = 2; }
  51628. var _this = _super.call(this) || this;
  51629. _this.exponent = exponent;
  51630. return _this;
  51631. }
  51632. ExponentialEase.prototype.easeInCore = function (gradient) {
  51633. if (this.exponent <= 0) {
  51634. return gradient;
  51635. }
  51636. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51637. };
  51638. return ExponentialEase;
  51639. }(EasingFunction));
  51640. BABYLON.ExponentialEase = ExponentialEase;
  51641. var PowerEase = /** @class */ (function (_super) {
  51642. __extends(PowerEase, _super);
  51643. function PowerEase(power) {
  51644. if (power === void 0) { power = 2; }
  51645. var _this = _super.call(this) || this;
  51646. _this.power = power;
  51647. return _this;
  51648. }
  51649. PowerEase.prototype.easeInCore = function (gradient) {
  51650. var y = Math.max(0.0, this.power);
  51651. return Math.pow(gradient, y);
  51652. };
  51653. return PowerEase;
  51654. }(EasingFunction));
  51655. BABYLON.PowerEase = PowerEase;
  51656. var QuadraticEase = /** @class */ (function (_super) {
  51657. __extends(QuadraticEase, _super);
  51658. function QuadraticEase() {
  51659. return _super !== null && _super.apply(this, arguments) || this;
  51660. }
  51661. QuadraticEase.prototype.easeInCore = function (gradient) {
  51662. return (gradient * gradient);
  51663. };
  51664. return QuadraticEase;
  51665. }(EasingFunction));
  51666. BABYLON.QuadraticEase = QuadraticEase;
  51667. var QuarticEase = /** @class */ (function (_super) {
  51668. __extends(QuarticEase, _super);
  51669. function QuarticEase() {
  51670. return _super !== null && _super.apply(this, arguments) || this;
  51671. }
  51672. QuarticEase.prototype.easeInCore = function (gradient) {
  51673. return (gradient * gradient * gradient * gradient);
  51674. };
  51675. return QuarticEase;
  51676. }(EasingFunction));
  51677. BABYLON.QuarticEase = QuarticEase;
  51678. var QuinticEase = /** @class */ (function (_super) {
  51679. __extends(QuinticEase, _super);
  51680. function QuinticEase() {
  51681. return _super !== null && _super.apply(this, arguments) || this;
  51682. }
  51683. QuinticEase.prototype.easeInCore = function (gradient) {
  51684. return (gradient * gradient * gradient * gradient * gradient);
  51685. };
  51686. return QuinticEase;
  51687. }(EasingFunction));
  51688. BABYLON.QuinticEase = QuinticEase;
  51689. var SineEase = /** @class */ (function (_super) {
  51690. __extends(SineEase, _super);
  51691. function SineEase() {
  51692. return _super !== null && _super.apply(this, arguments) || this;
  51693. }
  51694. SineEase.prototype.easeInCore = function (gradient) {
  51695. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51696. };
  51697. return SineEase;
  51698. }(EasingFunction));
  51699. BABYLON.SineEase = SineEase;
  51700. var BezierCurveEase = /** @class */ (function (_super) {
  51701. __extends(BezierCurveEase, _super);
  51702. function BezierCurveEase(x1, y1, x2, y2) {
  51703. if (x1 === void 0) { x1 = 0; }
  51704. if (y1 === void 0) { y1 = 0; }
  51705. if (x2 === void 0) { x2 = 1; }
  51706. if (y2 === void 0) { y2 = 1; }
  51707. var _this = _super.call(this) || this;
  51708. _this.x1 = x1;
  51709. _this.y1 = y1;
  51710. _this.x2 = x2;
  51711. _this.y2 = y2;
  51712. return _this;
  51713. }
  51714. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51715. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51716. };
  51717. return BezierCurveEase;
  51718. }(EasingFunction));
  51719. BABYLON.BezierCurveEase = BezierCurveEase;
  51720. })(BABYLON || (BABYLON = {}));
  51721. //# sourceMappingURL=babylon.easing.js.map
  51722. "use strict";
  51723. var BABYLON;
  51724. (function (BABYLON) {
  51725. /**
  51726. * A Condition applied to an Action
  51727. */
  51728. var Condition = /** @class */ (function () {
  51729. /**
  51730. * Creates a new Condition
  51731. * @param actionManager the manager of the action the condition is applied to
  51732. */
  51733. function Condition(actionManager) {
  51734. this._actionManager = actionManager;
  51735. }
  51736. /**
  51737. * Check if the current condition is valid
  51738. * @returns a boolean
  51739. */
  51740. Condition.prototype.isValid = function () {
  51741. return true;
  51742. };
  51743. /**
  51744. * Internal only
  51745. * @ignore
  51746. */
  51747. Condition.prototype._getProperty = function (propertyPath) {
  51748. return this._actionManager._getProperty(propertyPath);
  51749. };
  51750. /**
  51751. * Internal only
  51752. * @ignore
  51753. */
  51754. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51755. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51756. };
  51757. /**
  51758. * Serialize placeholder for child classes
  51759. * @returns the serialized object
  51760. */
  51761. Condition.prototype.serialize = function () {
  51762. };
  51763. /**
  51764. * Internal only
  51765. * @ignore
  51766. */
  51767. Condition.prototype._serialize = function (serializedCondition) {
  51768. return {
  51769. type: 2,
  51770. children: [],
  51771. name: serializedCondition.name,
  51772. properties: serializedCondition.properties
  51773. };
  51774. };
  51775. return Condition;
  51776. }());
  51777. BABYLON.Condition = Condition;
  51778. /**
  51779. * Defines specific conditional operators as extensions of Condition
  51780. */
  51781. var ValueCondition = /** @class */ (function (_super) {
  51782. __extends(ValueCondition, _super);
  51783. /**
  51784. * Creates a new ValueCondition
  51785. * @param actionManager manager for the action the condition applies to
  51786. * @param target for the action
  51787. * @param propertyPath path to specify the property of the target the conditional operator uses
  51788. * @param value the vale compared by the conditional operator against the current value of the property
  51789. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  51790. */
  51791. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  51792. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51793. var _this = _super.call(this, actionManager) || this;
  51794. _this.propertyPath = propertyPath;
  51795. _this.value = value;
  51796. _this.operator = operator;
  51797. _this._target = target;
  51798. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51799. _this._property = _this._getProperty(_this.propertyPath);
  51800. return _this;
  51801. }
  51802. Object.defineProperty(ValueCondition, "IsEqual", {
  51803. /**
  51804. * returns the number for IsEqual
  51805. */
  51806. get: function () {
  51807. return ValueCondition._IsEqual;
  51808. },
  51809. enumerable: true,
  51810. configurable: true
  51811. });
  51812. Object.defineProperty(ValueCondition, "IsDifferent", {
  51813. /**
  51814. * Returns the number for IsDifferent
  51815. */
  51816. get: function () {
  51817. return ValueCondition._IsDifferent;
  51818. },
  51819. enumerable: true,
  51820. configurable: true
  51821. });
  51822. Object.defineProperty(ValueCondition, "IsGreater", {
  51823. /**
  51824. * Returns the number for IsGreater
  51825. */
  51826. get: function () {
  51827. return ValueCondition._IsGreater;
  51828. },
  51829. enumerable: true,
  51830. configurable: true
  51831. });
  51832. Object.defineProperty(ValueCondition, "IsLesser", {
  51833. /**
  51834. * Returns the number for IsLesser
  51835. */
  51836. get: function () {
  51837. return ValueCondition._IsLesser;
  51838. },
  51839. enumerable: true,
  51840. configurable: true
  51841. });
  51842. /**
  51843. * Compares the given value with the property value for the specified conditional operator
  51844. * @returns the result of the comparison
  51845. */
  51846. ValueCondition.prototype.isValid = function () {
  51847. switch (this.operator) {
  51848. case ValueCondition.IsGreater:
  51849. return this._effectiveTarget[this._property] > this.value;
  51850. case ValueCondition.IsLesser:
  51851. return this._effectiveTarget[this._property] < this.value;
  51852. case ValueCondition.IsEqual:
  51853. case ValueCondition.IsDifferent:
  51854. var check;
  51855. if (this.value.equals) {
  51856. check = this.value.equals(this._effectiveTarget[this._property]);
  51857. }
  51858. else {
  51859. check = this.value === this._effectiveTarget[this._property];
  51860. }
  51861. return this.operator === ValueCondition.IsEqual ? check : !check;
  51862. }
  51863. return false;
  51864. };
  51865. /**
  51866. * Serialize the ValueCondition into a JSON compatible object
  51867. * @returns serialization object
  51868. */
  51869. ValueCondition.prototype.serialize = function () {
  51870. return this._serialize({
  51871. name: "ValueCondition",
  51872. properties: [
  51873. BABYLON.Action._GetTargetProperty(this._target),
  51874. { name: "propertyPath", value: this.propertyPath },
  51875. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51876. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51877. ]
  51878. });
  51879. };
  51880. /**
  51881. * Gets the name of the conditional operator for the ValueCondition
  51882. * @param operator the conditional operator
  51883. * @returns the name
  51884. */
  51885. ValueCondition.GetOperatorName = function (operator) {
  51886. switch (operator) {
  51887. case ValueCondition._IsEqual: return "IsEqual";
  51888. case ValueCondition._IsDifferent: return "IsDifferent";
  51889. case ValueCondition._IsGreater: return "IsGreater";
  51890. case ValueCondition._IsLesser: return "IsLesser";
  51891. default: return "";
  51892. }
  51893. };
  51894. /**
  51895. * Internal only
  51896. * @ignore
  51897. */
  51898. ValueCondition._IsEqual = 0;
  51899. /**
  51900. * Internal only
  51901. * @ignore
  51902. */
  51903. ValueCondition._IsDifferent = 1;
  51904. /**
  51905. * Internal only
  51906. * @ignore
  51907. */
  51908. ValueCondition._IsGreater = 2;
  51909. /**
  51910. * Internal only
  51911. * @ignore
  51912. */
  51913. ValueCondition._IsLesser = 3;
  51914. return ValueCondition;
  51915. }(Condition));
  51916. BABYLON.ValueCondition = ValueCondition;
  51917. /**
  51918. * Defines a predicate condition as an extension of Condition
  51919. */
  51920. var PredicateCondition = /** @class */ (function (_super) {
  51921. __extends(PredicateCondition, _super);
  51922. /**
  51923. * Creates a new {BABYLON.PredicateCondition}
  51924. * @param actionManager manager for the action the condition applies to
  51925. * @param predicate
  51926. */
  51927. function PredicateCondition(actionManager, predicate) {
  51928. var _this = _super.call(this, actionManager) || this;
  51929. _this.predicate = predicate;
  51930. return _this;
  51931. }
  51932. /**
  51933. * @returns the validity of the predicate condition
  51934. */
  51935. PredicateCondition.prototype.isValid = function () {
  51936. return this.predicate();
  51937. };
  51938. return PredicateCondition;
  51939. }(Condition));
  51940. BABYLON.PredicateCondition = PredicateCondition;
  51941. /**
  51942. * Defines a state condition as an extension of {BABYLON.Condition}
  51943. */
  51944. var StateCondition = /** @class */ (function (_super) {
  51945. __extends(StateCondition, _super);
  51946. /**
  51947. * Creates a new {BABYLON.StateCondition}
  51948. * @param actionManager manager for the action the condition applies to
  51949. * @param target of the condition
  51950. * @param value to compare with target state
  51951. */
  51952. function StateCondition(actionManager, target, value) {
  51953. var _this = _super.call(this, actionManager) || this;
  51954. _this.value = value;
  51955. _this._target = target;
  51956. return _this;
  51957. }
  51958. /**
  51959. * @returns the validity of the state
  51960. */
  51961. StateCondition.prototype.isValid = function () {
  51962. return this._target.state === this.value;
  51963. };
  51964. /**
  51965. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51966. * @returns serialization object
  51967. */
  51968. StateCondition.prototype.serialize = function () {
  51969. return this._serialize({
  51970. name: "StateCondition",
  51971. properties: [
  51972. BABYLON.Action._GetTargetProperty(this._target),
  51973. { name: "value", value: this.value }
  51974. ]
  51975. });
  51976. };
  51977. return StateCondition;
  51978. }(Condition));
  51979. BABYLON.StateCondition = StateCondition;
  51980. })(BABYLON || (BABYLON = {}));
  51981. //# sourceMappingURL=babylon.condition.js.map
  51982. "use strict";
  51983. var BABYLON;
  51984. (function (BABYLON) {
  51985. /**
  51986. * The action to be carried out following a trigger
  51987. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51988. */
  51989. var Action = /** @class */ (function () {
  51990. /**
  51991. * Creates a new Action
  51992. * @param triggerOptions the trigger, with or without parameters, for the action
  51993. * @param condition an optional determinant of action
  51994. */
  51995. function Action(triggerOptions, condition) {
  51996. this.triggerOptions = triggerOptions;
  51997. /**
  51998. * An event triggered prior to action being executed.
  51999. */
  52000. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52001. if (triggerOptions.parameter) {
  52002. this.trigger = triggerOptions.trigger;
  52003. this._triggerParameter = triggerOptions.parameter;
  52004. }
  52005. else {
  52006. this.trigger = triggerOptions;
  52007. }
  52008. this._nextActiveAction = this;
  52009. this._condition = condition;
  52010. }
  52011. /**
  52012. * Internal only
  52013. * @ignore
  52014. */
  52015. Action.prototype._prepare = function () {
  52016. };
  52017. /**
  52018. * Gets the trigger parameters
  52019. * @returns the trigger parameters
  52020. */
  52021. Action.prototype.getTriggerParameter = function () {
  52022. return this._triggerParameter;
  52023. };
  52024. /**
  52025. * Internal only - executes current action event
  52026. * @ignore
  52027. */
  52028. Action.prototype._executeCurrent = function (evt) {
  52029. if (this._nextActiveAction._condition) {
  52030. var condition = this._nextActiveAction._condition;
  52031. var currentRenderId = this._actionManager.getScene().getRenderId();
  52032. // We cache the current evaluation for the current frame
  52033. if (condition._evaluationId === currentRenderId) {
  52034. if (!condition._currentResult) {
  52035. return;
  52036. }
  52037. }
  52038. else {
  52039. condition._evaluationId = currentRenderId;
  52040. if (!condition.isValid()) {
  52041. condition._currentResult = false;
  52042. return;
  52043. }
  52044. condition._currentResult = true;
  52045. }
  52046. }
  52047. this.onBeforeExecuteObservable.notifyObservers(this);
  52048. this._nextActiveAction.execute(evt);
  52049. this.skipToNextActiveAction();
  52050. };
  52051. /**
  52052. * Execute placeholder for child classes
  52053. * @param evt optional action event
  52054. */
  52055. Action.prototype.execute = function (evt) {
  52056. };
  52057. /**
  52058. * Skips to next active action
  52059. */
  52060. Action.prototype.skipToNextActiveAction = function () {
  52061. if (this._nextActiveAction._child) {
  52062. if (!this._nextActiveAction._child._actionManager) {
  52063. this._nextActiveAction._child._actionManager = this._actionManager;
  52064. }
  52065. this._nextActiveAction = this._nextActiveAction._child;
  52066. }
  52067. else {
  52068. this._nextActiveAction = this;
  52069. }
  52070. };
  52071. /**
  52072. * Adds action to chain of actions, may be a DoNothingAction
  52073. * @param index The index of the attribute.
  52074. * @returns The action passed in
  52075. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52076. */
  52077. Action.prototype.then = function (action) {
  52078. this._child = action;
  52079. action._actionManager = this._actionManager;
  52080. action._prepare();
  52081. return action;
  52082. };
  52083. /**
  52084. * Internal only
  52085. * @ignore
  52086. */
  52087. Action.prototype._getProperty = function (propertyPath) {
  52088. return this._actionManager._getProperty(propertyPath);
  52089. };
  52090. /**
  52091. * Internal only
  52092. * @ignore
  52093. */
  52094. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52095. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52096. };
  52097. /**
  52098. * Serialize placeholder for child classes
  52099. * @param parent of child
  52100. * @returns the serialized object
  52101. */
  52102. Action.prototype.serialize = function (parent) {
  52103. };
  52104. /**
  52105. * Internal only called by serialize
  52106. * @ignore
  52107. */
  52108. Action.prototype._serialize = function (serializedAction, parent) {
  52109. var serializationObject = {
  52110. type: 1,
  52111. children: [],
  52112. name: serializedAction.name,
  52113. properties: serializedAction.properties || []
  52114. };
  52115. // Serialize child
  52116. if (this._child) {
  52117. this._child.serialize(serializationObject);
  52118. }
  52119. // Check if "this" has a condition
  52120. if (this._condition) {
  52121. var serializedCondition = this._condition.serialize();
  52122. serializedCondition.children.push(serializationObject);
  52123. if (parent) {
  52124. parent.children.push(serializedCondition);
  52125. }
  52126. return serializedCondition;
  52127. }
  52128. if (parent) {
  52129. parent.children.push(serializationObject);
  52130. }
  52131. return serializationObject;
  52132. };
  52133. /**
  52134. * Internal only
  52135. * @ignore
  52136. */
  52137. Action._SerializeValueAsString = function (value) {
  52138. if (typeof value === "number") {
  52139. return value.toString();
  52140. }
  52141. if (typeof value === "boolean") {
  52142. return value ? "true" : "false";
  52143. }
  52144. if (value instanceof BABYLON.Vector2) {
  52145. return value.x + ", " + value.y;
  52146. }
  52147. if (value instanceof BABYLON.Vector3) {
  52148. return value.x + ", " + value.y + ", " + value.z;
  52149. }
  52150. if (value instanceof BABYLON.Color3) {
  52151. return value.r + ", " + value.g + ", " + value.b;
  52152. }
  52153. if (value instanceof BABYLON.Color4) {
  52154. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52155. }
  52156. return value; // string
  52157. };
  52158. /**
  52159. * Internal only
  52160. * @ignore
  52161. */
  52162. Action._GetTargetProperty = function (target) {
  52163. return {
  52164. name: "target",
  52165. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52166. : target instanceof BABYLON.Light ? "LightProperties"
  52167. : target instanceof BABYLON.Camera ? "CameraProperties"
  52168. : "SceneProperties",
  52169. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52170. };
  52171. };
  52172. return Action;
  52173. }());
  52174. BABYLON.Action = Action;
  52175. })(BABYLON || (BABYLON = {}));
  52176. //# sourceMappingURL=babylon.action.js.map
  52177. "use strict";
  52178. var BABYLON;
  52179. (function (BABYLON) {
  52180. /**
  52181. * ActionEvent is the event being sent when an action is triggered.
  52182. */
  52183. var ActionEvent = /** @class */ (function () {
  52184. /**
  52185. * @param source The mesh or sprite that triggered the action.
  52186. * @param pointerX The X mouse cursor position at the time of the event
  52187. * @param pointerY The Y mouse cursor position at the time of the event
  52188. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52189. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52190. */
  52191. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52192. this.source = source;
  52193. this.pointerX = pointerX;
  52194. this.pointerY = pointerY;
  52195. this.meshUnderPointer = meshUnderPointer;
  52196. this.sourceEvent = sourceEvent;
  52197. this.additionalData = additionalData;
  52198. }
  52199. /**
  52200. * Helper function to auto-create an ActionEvent from a source mesh.
  52201. * @param source The source mesh that triggered the event
  52202. * @param evt {Event} The original (browser) event
  52203. */
  52204. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52205. var scene = source.getScene();
  52206. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52207. };
  52208. /**
  52209. * Helper function to auto-create an ActionEvent from a source mesh.
  52210. * @param source The source sprite that triggered the event
  52211. * @param scene Scene associated with the sprite
  52212. * @param evt {Event} The original (browser) event
  52213. */
  52214. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52215. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52216. };
  52217. /**
  52218. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52219. * @param scene the scene where the event occurred
  52220. * @param evt {Event} The original (browser) event
  52221. */
  52222. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52223. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52224. };
  52225. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52226. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52227. };
  52228. return ActionEvent;
  52229. }());
  52230. BABYLON.ActionEvent = ActionEvent;
  52231. /**
  52232. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52233. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52234. */
  52235. var ActionManager = /** @class */ (function () {
  52236. function ActionManager(scene) {
  52237. // Members
  52238. this.actions = new Array();
  52239. this.hoverCursor = '';
  52240. this._scene = scene;
  52241. scene._actionManagers.push(this);
  52242. }
  52243. Object.defineProperty(ActionManager, "NothingTrigger", {
  52244. get: function () {
  52245. return ActionManager._NothingTrigger;
  52246. },
  52247. enumerable: true,
  52248. configurable: true
  52249. });
  52250. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52251. get: function () {
  52252. return ActionManager._OnPickTrigger;
  52253. },
  52254. enumerable: true,
  52255. configurable: true
  52256. });
  52257. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52258. get: function () {
  52259. return ActionManager._OnLeftPickTrigger;
  52260. },
  52261. enumerable: true,
  52262. configurable: true
  52263. });
  52264. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52265. get: function () {
  52266. return ActionManager._OnRightPickTrigger;
  52267. },
  52268. enumerable: true,
  52269. configurable: true
  52270. });
  52271. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52272. get: function () {
  52273. return ActionManager._OnCenterPickTrigger;
  52274. },
  52275. enumerable: true,
  52276. configurable: true
  52277. });
  52278. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52279. get: function () {
  52280. return ActionManager._OnPickDownTrigger;
  52281. },
  52282. enumerable: true,
  52283. configurable: true
  52284. });
  52285. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52286. get: function () {
  52287. return ActionManager._OnDoublePickTrigger;
  52288. },
  52289. enumerable: true,
  52290. configurable: true
  52291. });
  52292. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52293. get: function () {
  52294. return ActionManager._OnPickUpTrigger;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52300. /// This trigger will only be raised if you also declared a OnPickDown
  52301. get: function () {
  52302. return ActionManager._OnPickOutTrigger;
  52303. },
  52304. enumerable: true,
  52305. configurable: true
  52306. });
  52307. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52308. get: function () {
  52309. return ActionManager._OnLongPressTrigger;
  52310. },
  52311. enumerable: true,
  52312. configurable: true
  52313. });
  52314. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52315. get: function () {
  52316. return ActionManager._OnPointerOverTrigger;
  52317. },
  52318. enumerable: true,
  52319. configurable: true
  52320. });
  52321. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52322. get: function () {
  52323. return ActionManager._OnPointerOutTrigger;
  52324. },
  52325. enumerable: true,
  52326. configurable: true
  52327. });
  52328. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52329. get: function () {
  52330. return ActionManager._OnEveryFrameTrigger;
  52331. },
  52332. enumerable: true,
  52333. configurable: true
  52334. });
  52335. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52336. get: function () {
  52337. return ActionManager._OnIntersectionEnterTrigger;
  52338. },
  52339. enumerable: true,
  52340. configurable: true
  52341. });
  52342. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52343. get: function () {
  52344. return ActionManager._OnIntersectionExitTrigger;
  52345. },
  52346. enumerable: true,
  52347. configurable: true
  52348. });
  52349. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52350. get: function () {
  52351. return ActionManager._OnKeyDownTrigger;
  52352. },
  52353. enumerable: true,
  52354. configurable: true
  52355. });
  52356. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52357. get: function () {
  52358. return ActionManager._OnKeyUpTrigger;
  52359. },
  52360. enumerable: true,
  52361. configurable: true
  52362. });
  52363. // Methods
  52364. ActionManager.prototype.dispose = function () {
  52365. var index = this._scene._actionManagers.indexOf(this);
  52366. for (var i = 0; i < this.actions.length; i++) {
  52367. var action = this.actions[i];
  52368. ActionManager.Triggers[action.trigger]--;
  52369. if (ActionManager.Triggers[action.trigger] === 0) {
  52370. delete ActionManager.Triggers[action.trigger];
  52371. }
  52372. }
  52373. if (index > -1) {
  52374. this._scene._actionManagers.splice(index, 1);
  52375. }
  52376. };
  52377. ActionManager.prototype.getScene = function () {
  52378. return this._scene;
  52379. };
  52380. /**
  52381. * Does this action manager handles actions of any of the given triggers
  52382. * @param {number[]} triggers - the triggers to be tested
  52383. * @return {boolean} whether one (or more) of the triggers is handeled
  52384. */
  52385. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52386. for (var index = 0; index < this.actions.length; index++) {
  52387. var action = this.actions[index];
  52388. if (triggers.indexOf(action.trigger) > -1) {
  52389. return true;
  52390. }
  52391. }
  52392. return false;
  52393. };
  52394. /**
  52395. * Does this action manager handles actions of a given trigger
  52396. * @param trigger defines the trigger to be tested
  52397. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52398. * @return whether the trigger is handled
  52399. */
  52400. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52401. for (var index = 0; index < this.actions.length; index++) {
  52402. var action = this.actions[index];
  52403. if (action.trigger === trigger) {
  52404. if (parameterPredicate) {
  52405. if (parameterPredicate(action.getTriggerParameter())) {
  52406. return true;
  52407. }
  52408. }
  52409. else {
  52410. return true;
  52411. }
  52412. }
  52413. }
  52414. return false;
  52415. };
  52416. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52417. /**
  52418. * Does this action manager has pointer triggers
  52419. * @return {boolean} whether or not it has pointer triggers
  52420. */
  52421. get: function () {
  52422. for (var index = 0; index < this.actions.length; index++) {
  52423. var action = this.actions[index];
  52424. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52425. return true;
  52426. }
  52427. }
  52428. return false;
  52429. },
  52430. enumerable: true,
  52431. configurable: true
  52432. });
  52433. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52434. /**
  52435. * Does this action manager has pick triggers
  52436. * @return {boolean} whether or not it has pick triggers
  52437. */
  52438. get: function () {
  52439. for (var index = 0; index < this.actions.length; index++) {
  52440. var action = this.actions[index];
  52441. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52442. return true;
  52443. }
  52444. }
  52445. return false;
  52446. },
  52447. enumerable: true,
  52448. configurable: true
  52449. });
  52450. Object.defineProperty(ActionManager, "HasTriggers", {
  52451. /**
  52452. * Does exist one action manager with at least one trigger
  52453. * @return {boolean} whether or not it exists one action manager with one trigger
  52454. **/
  52455. get: function () {
  52456. for (var t in ActionManager.Triggers) {
  52457. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52458. return true;
  52459. }
  52460. }
  52461. return false;
  52462. },
  52463. enumerable: true,
  52464. configurable: true
  52465. });
  52466. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52467. /**
  52468. * Does exist one action manager with at least one pick trigger
  52469. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52470. **/
  52471. get: function () {
  52472. for (var t in ActionManager.Triggers) {
  52473. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52474. var t_int = parseInt(t);
  52475. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52476. return true;
  52477. }
  52478. }
  52479. }
  52480. return false;
  52481. },
  52482. enumerable: true,
  52483. configurable: true
  52484. });
  52485. /**
  52486. * Does exist one action manager that handles actions of a given trigger
  52487. * @param {number} trigger - the trigger to be tested
  52488. * @return {boolean} whether the trigger is handeled by at least one action manager
  52489. **/
  52490. ActionManager.HasSpecificTrigger = function (trigger) {
  52491. for (var t in ActionManager.Triggers) {
  52492. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52493. var t_int = parseInt(t);
  52494. if (t_int === trigger) {
  52495. return true;
  52496. }
  52497. }
  52498. }
  52499. return false;
  52500. };
  52501. /**
  52502. * Registers an action to this action manager
  52503. * @param {BABYLON.Action} action - the action to be registered
  52504. * @return {BABYLON.Action} the action amended (prepared) after registration
  52505. */
  52506. ActionManager.prototype.registerAction = function (action) {
  52507. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52508. if (this.getScene().actionManager !== this) {
  52509. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52510. return null;
  52511. }
  52512. }
  52513. this.actions.push(action);
  52514. if (ActionManager.Triggers[action.trigger]) {
  52515. ActionManager.Triggers[action.trigger]++;
  52516. }
  52517. else {
  52518. ActionManager.Triggers[action.trigger] = 1;
  52519. }
  52520. action._actionManager = this;
  52521. action._prepare();
  52522. return action;
  52523. };
  52524. /**
  52525. * Unregisters an action to this action manager
  52526. * @param action The action to be unregistered
  52527. * @return whether the action has been unregistered
  52528. */
  52529. ActionManager.prototype.unregisterAction = function (action) {
  52530. var index = this.actions.indexOf(action);
  52531. if (index !== -1) {
  52532. this.actions.splice(index, 1);
  52533. ActionManager.Triggers[action.trigger] -= 1;
  52534. if (ActionManager.Triggers[action.trigger] === 0) {
  52535. delete ActionManager.Triggers[action.trigger];
  52536. }
  52537. delete action._actionManager;
  52538. return true;
  52539. }
  52540. return false;
  52541. };
  52542. /**
  52543. * Process a specific trigger
  52544. * @param {number} trigger - the trigger to process
  52545. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52546. */
  52547. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52548. for (var index = 0; index < this.actions.length; index++) {
  52549. var action = this.actions[index];
  52550. if (action.trigger === trigger) {
  52551. if (evt) {
  52552. if (trigger === ActionManager.OnKeyUpTrigger
  52553. || trigger === ActionManager.OnKeyDownTrigger) {
  52554. var parameter = action.getTriggerParameter();
  52555. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52556. if (!parameter.toLowerCase) {
  52557. continue;
  52558. }
  52559. var lowerCase = parameter.toLowerCase();
  52560. if (lowerCase !== evt.sourceEvent.key) {
  52561. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52562. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52563. if (actualkey !== lowerCase) {
  52564. continue;
  52565. }
  52566. }
  52567. }
  52568. }
  52569. }
  52570. action._executeCurrent(evt);
  52571. }
  52572. }
  52573. };
  52574. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52575. var properties = propertyPath.split(".");
  52576. for (var index = 0; index < properties.length - 1; index++) {
  52577. target = target[properties[index]];
  52578. }
  52579. return target;
  52580. };
  52581. ActionManager.prototype._getProperty = function (propertyPath) {
  52582. var properties = propertyPath.split(".");
  52583. return properties[properties.length - 1];
  52584. };
  52585. ActionManager.prototype.serialize = function (name) {
  52586. var root = {
  52587. children: new Array(),
  52588. name: name,
  52589. type: 3,
  52590. properties: new Array() // Empty for root but required
  52591. };
  52592. for (var i = 0; i < this.actions.length; i++) {
  52593. var triggerObject = {
  52594. type: 0,
  52595. children: new Array(),
  52596. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52597. properties: new Array()
  52598. };
  52599. var triggerOptions = this.actions[i].triggerOptions;
  52600. if (triggerOptions && typeof triggerOptions !== "number") {
  52601. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52602. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52603. }
  52604. else {
  52605. var parameter = {};
  52606. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52607. if (triggerOptions.parameter.mesh) {
  52608. parameter._meshId = triggerOptions.parameter.mesh.id;
  52609. }
  52610. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52611. }
  52612. }
  52613. // Serialize child action, recursively
  52614. this.actions[i].serialize(triggerObject);
  52615. // Add serialized trigger
  52616. root.children.push(triggerObject);
  52617. }
  52618. return root;
  52619. };
  52620. ActionManager.Parse = function (parsedActions, object, scene) {
  52621. var actionManager = new ActionManager(scene);
  52622. if (object === null)
  52623. scene.actionManager = actionManager;
  52624. else
  52625. object.actionManager = actionManager;
  52626. // instanciate a new object
  52627. var instanciate = function (name, params) {
  52628. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52629. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52630. newInstance.constructor.apply(newInstance, params);
  52631. return newInstance;
  52632. };
  52633. var parseParameter = function (name, value, target, propertyPath) {
  52634. if (propertyPath === null) {
  52635. // String, boolean or float
  52636. var floatValue = parseFloat(value);
  52637. if (value === "true" || value === "false")
  52638. return value === "true";
  52639. else
  52640. return isNaN(floatValue) ? value : floatValue;
  52641. }
  52642. var effectiveTarget = propertyPath.split(".");
  52643. var values = value.split(",");
  52644. // Get effective Target
  52645. for (var i = 0; i < effectiveTarget.length; i++) {
  52646. target = target[effectiveTarget[i]];
  52647. }
  52648. // Return appropriate value with its type
  52649. if (typeof (target) === "boolean")
  52650. return values[0] === "true";
  52651. if (typeof (target) === "string")
  52652. return values[0];
  52653. // Parameters with multiple values such as Vector3 etc.
  52654. var split = new Array();
  52655. for (var i = 0; i < values.length; i++)
  52656. split.push(parseFloat(values[i]));
  52657. if (target instanceof BABYLON.Vector3)
  52658. return BABYLON.Vector3.FromArray(split);
  52659. if (target instanceof BABYLON.Vector4)
  52660. return BABYLON.Vector4.FromArray(split);
  52661. if (target instanceof BABYLON.Color3)
  52662. return BABYLON.Color3.FromArray(split);
  52663. if (target instanceof BABYLON.Color4)
  52664. return BABYLON.Color4.FromArray(split);
  52665. return parseFloat(values[0]);
  52666. };
  52667. // traverse graph per trigger
  52668. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52669. if (combineArray === void 0) { combineArray = null; }
  52670. if (parsedAction.detached)
  52671. return;
  52672. var parameters = new Array();
  52673. var target = null;
  52674. var propertyPath = null;
  52675. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52676. // Parameters
  52677. if (parsedAction.type === 2)
  52678. parameters.push(actionManager);
  52679. else
  52680. parameters.push(trigger);
  52681. if (combine) {
  52682. var actions = new Array();
  52683. for (var j = 0; j < parsedAction.combine.length; j++) {
  52684. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52685. }
  52686. parameters.push(actions);
  52687. }
  52688. else {
  52689. for (var i = 0; i < parsedAction.properties.length; i++) {
  52690. var value = parsedAction.properties[i].value;
  52691. var name = parsedAction.properties[i].name;
  52692. var targetType = parsedAction.properties[i].targetType;
  52693. if (name === "target")
  52694. if (targetType !== null && targetType === "SceneProperties")
  52695. value = target = scene;
  52696. else
  52697. value = target = scene.getNodeByName(value);
  52698. else if (name === "parent")
  52699. value = scene.getNodeByName(value);
  52700. else if (name === "sound")
  52701. value = scene.getSoundByName(value);
  52702. else if (name !== "propertyPath") {
  52703. if (parsedAction.type === 2 && name === "operator")
  52704. value = BABYLON.ValueCondition[value];
  52705. else
  52706. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52707. }
  52708. else {
  52709. propertyPath = value;
  52710. }
  52711. parameters.push(value);
  52712. }
  52713. }
  52714. if (combineArray === null) {
  52715. parameters.push(condition);
  52716. }
  52717. else {
  52718. parameters.push(null);
  52719. }
  52720. // If interpolate value action
  52721. if (parsedAction.name === "InterpolateValueAction") {
  52722. var param = parameters[parameters.length - 2];
  52723. parameters[parameters.length - 1] = param;
  52724. parameters[parameters.length - 2] = condition;
  52725. }
  52726. // Action or condition(s) and not CombineAction
  52727. var newAction = instanciate(parsedAction.name, parameters);
  52728. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52729. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52730. if (action)
  52731. action.then(nothing);
  52732. else
  52733. actionManager.registerAction(nothing);
  52734. action = nothing;
  52735. }
  52736. if (combineArray === null) {
  52737. if (newAction instanceof BABYLON.Condition) {
  52738. condition = newAction;
  52739. newAction = action;
  52740. }
  52741. else {
  52742. condition = null;
  52743. if (action)
  52744. action.then(newAction);
  52745. else
  52746. actionManager.registerAction(newAction);
  52747. }
  52748. }
  52749. else {
  52750. combineArray.push(newAction);
  52751. }
  52752. for (var i = 0; i < parsedAction.children.length; i++)
  52753. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52754. };
  52755. // triggers
  52756. for (var i = 0; i < parsedActions.children.length; i++) {
  52757. var triggerParams;
  52758. var trigger = parsedActions.children[i];
  52759. if (trigger.properties.length > 0) {
  52760. var param = trigger.properties[0].value;
  52761. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52762. if (value._meshId) {
  52763. value.mesh = scene.getMeshByID(value._meshId);
  52764. }
  52765. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52766. }
  52767. else
  52768. triggerParams = ActionManager[trigger.name];
  52769. for (var j = 0; j < trigger.children.length; j++) {
  52770. if (!trigger.detached)
  52771. traverse(trigger.children[j], triggerParams, null, null);
  52772. }
  52773. }
  52774. };
  52775. ActionManager.GetTriggerName = function (trigger) {
  52776. switch (trigger) {
  52777. case 0: return "NothingTrigger";
  52778. case 1: return "OnPickTrigger";
  52779. case 2: return "OnLeftPickTrigger";
  52780. case 3: return "OnRightPickTrigger";
  52781. case 4: return "OnCenterPickTrigger";
  52782. case 5: return "OnPickDownTrigger";
  52783. case 6: return "OnPickUpTrigger";
  52784. case 7: return "OnLongPressTrigger";
  52785. case 8: return "OnPointerOverTrigger";
  52786. case 9: return "OnPointerOutTrigger";
  52787. case 10: return "OnEveryFrameTrigger";
  52788. case 11: return "OnIntersectionEnterTrigger";
  52789. case 12: return "OnIntersectionExitTrigger";
  52790. case 13: return "OnKeyDownTrigger";
  52791. case 14: return "OnKeyUpTrigger";
  52792. case 15: return "OnPickOutTrigger";
  52793. default: return "";
  52794. }
  52795. };
  52796. // Statics
  52797. ActionManager._NothingTrigger = 0;
  52798. ActionManager._OnPickTrigger = 1;
  52799. ActionManager._OnLeftPickTrigger = 2;
  52800. ActionManager._OnRightPickTrigger = 3;
  52801. ActionManager._OnCenterPickTrigger = 4;
  52802. ActionManager._OnPickDownTrigger = 5;
  52803. ActionManager._OnDoublePickTrigger = 6;
  52804. ActionManager._OnPickUpTrigger = 7;
  52805. ActionManager._OnLongPressTrigger = 8;
  52806. ActionManager._OnPointerOverTrigger = 9;
  52807. ActionManager._OnPointerOutTrigger = 10;
  52808. ActionManager._OnEveryFrameTrigger = 11;
  52809. ActionManager._OnIntersectionEnterTrigger = 12;
  52810. ActionManager._OnIntersectionExitTrigger = 13;
  52811. ActionManager._OnKeyDownTrigger = 14;
  52812. ActionManager._OnKeyUpTrigger = 15;
  52813. ActionManager._OnPickOutTrigger = 16;
  52814. ActionManager.Triggers = {};
  52815. return ActionManager;
  52816. }());
  52817. BABYLON.ActionManager = ActionManager;
  52818. })(BABYLON || (BABYLON = {}));
  52819. //# sourceMappingURL=babylon.actionManager.js.map
  52820. "use strict";
  52821. var BABYLON;
  52822. (function (BABYLON) {
  52823. var InterpolateValueAction = /** @class */ (function (_super) {
  52824. __extends(InterpolateValueAction, _super);
  52825. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52826. if (duration === void 0) { duration = 1000; }
  52827. var _this = _super.call(this, triggerOptions, condition) || this;
  52828. _this.propertyPath = propertyPath;
  52829. _this.value = value;
  52830. _this.duration = duration;
  52831. _this.stopOtherAnimations = stopOtherAnimations;
  52832. _this.onInterpolationDone = onInterpolationDone;
  52833. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52834. _this._target = _this._effectiveTarget = target;
  52835. return _this;
  52836. }
  52837. InterpolateValueAction.prototype._prepare = function () {
  52838. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52839. this._property = this._getProperty(this.propertyPath);
  52840. };
  52841. InterpolateValueAction.prototype.execute = function () {
  52842. var _this = this;
  52843. var scene = this._actionManager.getScene();
  52844. var keys = [
  52845. {
  52846. frame: 0,
  52847. value: this._effectiveTarget[this._property]
  52848. }, {
  52849. frame: 100,
  52850. value: this.value
  52851. }
  52852. ];
  52853. var dataType;
  52854. if (typeof this.value === "number") {
  52855. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52856. }
  52857. else if (this.value instanceof BABYLON.Color3) {
  52858. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52859. }
  52860. else if (this.value instanceof BABYLON.Vector3) {
  52861. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52862. }
  52863. else if (this.value instanceof BABYLON.Matrix) {
  52864. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52865. }
  52866. else if (this.value instanceof BABYLON.Quaternion) {
  52867. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52868. }
  52869. else {
  52870. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52871. return;
  52872. }
  52873. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52874. animation.setKeys(keys);
  52875. if (this.stopOtherAnimations) {
  52876. scene.stopAnimation(this._effectiveTarget);
  52877. }
  52878. var wrapper = function () {
  52879. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52880. if (_this.onInterpolationDone) {
  52881. _this.onInterpolationDone();
  52882. }
  52883. };
  52884. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52885. };
  52886. InterpolateValueAction.prototype.serialize = function (parent) {
  52887. return _super.prototype._serialize.call(this, {
  52888. name: "InterpolateValueAction",
  52889. properties: [
  52890. BABYLON.Action._GetTargetProperty(this._target),
  52891. { name: "propertyPath", value: this.propertyPath },
  52892. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52893. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52894. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52895. ]
  52896. }, parent);
  52897. };
  52898. return InterpolateValueAction;
  52899. }(BABYLON.Action));
  52900. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52901. })(BABYLON || (BABYLON = {}));
  52902. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52903. "use strict";
  52904. var BABYLON;
  52905. (function (BABYLON) {
  52906. var SwitchBooleanAction = /** @class */ (function (_super) {
  52907. __extends(SwitchBooleanAction, _super);
  52908. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52909. var _this = _super.call(this, triggerOptions, condition) || this;
  52910. _this.propertyPath = propertyPath;
  52911. _this._target = _this._effectiveTarget = target;
  52912. return _this;
  52913. }
  52914. SwitchBooleanAction.prototype._prepare = function () {
  52915. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52916. this._property = this._getProperty(this.propertyPath);
  52917. };
  52918. SwitchBooleanAction.prototype.execute = function () {
  52919. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52920. };
  52921. SwitchBooleanAction.prototype.serialize = function (parent) {
  52922. return _super.prototype._serialize.call(this, {
  52923. name: "SwitchBooleanAction",
  52924. properties: [
  52925. BABYLON.Action._GetTargetProperty(this._target),
  52926. { name: "propertyPath", value: this.propertyPath }
  52927. ]
  52928. }, parent);
  52929. };
  52930. return SwitchBooleanAction;
  52931. }(BABYLON.Action));
  52932. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52933. var SetStateAction = /** @class */ (function (_super) {
  52934. __extends(SetStateAction, _super);
  52935. function SetStateAction(triggerOptions, target, value, condition) {
  52936. var _this = _super.call(this, triggerOptions, condition) || this;
  52937. _this.value = value;
  52938. _this._target = target;
  52939. return _this;
  52940. }
  52941. SetStateAction.prototype.execute = function () {
  52942. this._target.state = this.value;
  52943. };
  52944. SetStateAction.prototype.serialize = function (parent) {
  52945. return _super.prototype._serialize.call(this, {
  52946. name: "SetStateAction",
  52947. properties: [
  52948. BABYLON.Action._GetTargetProperty(this._target),
  52949. { name: "value", value: this.value }
  52950. ]
  52951. }, parent);
  52952. };
  52953. return SetStateAction;
  52954. }(BABYLON.Action));
  52955. BABYLON.SetStateAction = SetStateAction;
  52956. var SetValueAction = /** @class */ (function (_super) {
  52957. __extends(SetValueAction, _super);
  52958. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52959. var _this = _super.call(this, triggerOptions, condition) || this;
  52960. _this.propertyPath = propertyPath;
  52961. _this.value = value;
  52962. _this._target = _this._effectiveTarget = target;
  52963. return _this;
  52964. }
  52965. SetValueAction.prototype._prepare = function () {
  52966. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52967. this._property = this._getProperty(this.propertyPath);
  52968. };
  52969. SetValueAction.prototype.execute = function () {
  52970. this._effectiveTarget[this._property] = this.value;
  52971. if (this._target.markAsDirty) {
  52972. this._target.markAsDirty(this._property);
  52973. }
  52974. };
  52975. SetValueAction.prototype.serialize = function (parent) {
  52976. return _super.prototype._serialize.call(this, {
  52977. name: "SetValueAction",
  52978. properties: [
  52979. BABYLON.Action._GetTargetProperty(this._target),
  52980. { name: "propertyPath", value: this.propertyPath },
  52981. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52982. ]
  52983. }, parent);
  52984. };
  52985. return SetValueAction;
  52986. }(BABYLON.Action));
  52987. BABYLON.SetValueAction = SetValueAction;
  52988. var IncrementValueAction = /** @class */ (function (_super) {
  52989. __extends(IncrementValueAction, _super);
  52990. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52991. var _this = _super.call(this, triggerOptions, condition) || this;
  52992. _this.propertyPath = propertyPath;
  52993. _this.value = value;
  52994. _this._target = _this._effectiveTarget = target;
  52995. return _this;
  52996. }
  52997. IncrementValueAction.prototype._prepare = function () {
  52998. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52999. this._property = this._getProperty(this.propertyPath);
  53000. if (typeof this._effectiveTarget[this._property] !== "number") {
  53001. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53002. }
  53003. };
  53004. IncrementValueAction.prototype.execute = function () {
  53005. this._effectiveTarget[this._property] += this.value;
  53006. if (this._target.markAsDirty) {
  53007. this._target.markAsDirty(this._property);
  53008. }
  53009. };
  53010. IncrementValueAction.prototype.serialize = function (parent) {
  53011. return _super.prototype._serialize.call(this, {
  53012. name: "IncrementValueAction",
  53013. properties: [
  53014. BABYLON.Action._GetTargetProperty(this._target),
  53015. { name: "propertyPath", value: this.propertyPath },
  53016. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53017. ]
  53018. }, parent);
  53019. };
  53020. return IncrementValueAction;
  53021. }(BABYLON.Action));
  53022. BABYLON.IncrementValueAction = IncrementValueAction;
  53023. var PlayAnimationAction = /** @class */ (function (_super) {
  53024. __extends(PlayAnimationAction, _super);
  53025. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53026. var _this = _super.call(this, triggerOptions, condition) || this;
  53027. _this.from = from;
  53028. _this.to = to;
  53029. _this.loop = loop;
  53030. _this._target = target;
  53031. return _this;
  53032. }
  53033. PlayAnimationAction.prototype._prepare = function () {
  53034. };
  53035. PlayAnimationAction.prototype.execute = function () {
  53036. var scene = this._actionManager.getScene();
  53037. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53038. };
  53039. PlayAnimationAction.prototype.serialize = function (parent) {
  53040. return _super.prototype._serialize.call(this, {
  53041. name: "PlayAnimationAction",
  53042. properties: [
  53043. BABYLON.Action._GetTargetProperty(this._target),
  53044. { name: "from", value: String(this.from) },
  53045. { name: "to", value: String(this.to) },
  53046. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53047. ]
  53048. }, parent);
  53049. };
  53050. return PlayAnimationAction;
  53051. }(BABYLON.Action));
  53052. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53053. var StopAnimationAction = /** @class */ (function (_super) {
  53054. __extends(StopAnimationAction, _super);
  53055. function StopAnimationAction(triggerOptions, target, condition) {
  53056. var _this = _super.call(this, triggerOptions, condition) || this;
  53057. _this._target = target;
  53058. return _this;
  53059. }
  53060. StopAnimationAction.prototype._prepare = function () {
  53061. };
  53062. StopAnimationAction.prototype.execute = function () {
  53063. var scene = this._actionManager.getScene();
  53064. scene.stopAnimation(this._target);
  53065. };
  53066. StopAnimationAction.prototype.serialize = function (parent) {
  53067. return _super.prototype._serialize.call(this, {
  53068. name: "StopAnimationAction",
  53069. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53070. }, parent);
  53071. };
  53072. return StopAnimationAction;
  53073. }(BABYLON.Action));
  53074. BABYLON.StopAnimationAction = StopAnimationAction;
  53075. var DoNothingAction = /** @class */ (function (_super) {
  53076. __extends(DoNothingAction, _super);
  53077. function DoNothingAction(triggerOptions, condition) {
  53078. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53079. return _super.call(this, triggerOptions, condition) || this;
  53080. }
  53081. DoNothingAction.prototype.execute = function () {
  53082. };
  53083. DoNothingAction.prototype.serialize = function (parent) {
  53084. return _super.prototype._serialize.call(this, {
  53085. name: "DoNothingAction",
  53086. properties: []
  53087. }, parent);
  53088. };
  53089. return DoNothingAction;
  53090. }(BABYLON.Action));
  53091. BABYLON.DoNothingAction = DoNothingAction;
  53092. var CombineAction = /** @class */ (function (_super) {
  53093. __extends(CombineAction, _super);
  53094. function CombineAction(triggerOptions, children, condition) {
  53095. var _this = _super.call(this, triggerOptions, condition) || this;
  53096. _this.children = children;
  53097. return _this;
  53098. }
  53099. CombineAction.prototype._prepare = function () {
  53100. for (var index = 0; index < this.children.length; index++) {
  53101. this.children[index]._actionManager = this._actionManager;
  53102. this.children[index]._prepare();
  53103. }
  53104. };
  53105. CombineAction.prototype.execute = function (evt) {
  53106. for (var index = 0; index < this.children.length; index++) {
  53107. this.children[index].execute(evt);
  53108. }
  53109. };
  53110. CombineAction.prototype.serialize = function (parent) {
  53111. var serializationObject = _super.prototype._serialize.call(this, {
  53112. name: "CombineAction",
  53113. properties: [],
  53114. combine: []
  53115. }, parent);
  53116. for (var i = 0; i < this.children.length; i++) {
  53117. serializationObject.combine.push(this.children[i].serialize(null));
  53118. }
  53119. return serializationObject;
  53120. };
  53121. return CombineAction;
  53122. }(BABYLON.Action));
  53123. BABYLON.CombineAction = CombineAction;
  53124. var ExecuteCodeAction = /** @class */ (function (_super) {
  53125. __extends(ExecuteCodeAction, _super);
  53126. function ExecuteCodeAction(triggerOptions, func, condition) {
  53127. var _this = _super.call(this, triggerOptions, condition) || this;
  53128. _this.func = func;
  53129. return _this;
  53130. }
  53131. ExecuteCodeAction.prototype.execute = function (evt) {
  53132. this.func(evt);
  53133. };
  53134. return ExecuteCodeAction;
  53135. }(BABYLON.Action));
  53136. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53137. var SetParentAction = /** @class */ (function (_super) {
  53138. __extends(SetParentAction, _super);
  53139. function SetParentAction(triggerOptions, target, parent, condition) {
  53140. var _this = _super.call(this, triggerOptions, condition) || this;
  53141. _this._target = target;
  53142. _this._parent = parent;
  53143. return _this;
  53144. }
  53145. SetParentAction.prototype._prepare = function () {
  53146. };
  53147. SetParentAction.prototype.execute = function () {
  53148. if (this._target.parent === this._parent) {
  53149. return;
  53150. }
  53151. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53152. invertParentWorldMatrix.invert();
  53153. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53154. this._target.parent = this._parent;
  53155. };
  53156. SetParentAction.prototype.serialize = function (parent) {
  53157. return _super.prototype._serialize.call(this, {
  53158. name: "SetParentAction",
  53159. properties: [
  53160. BABYLON.Action._GetTargetProperty(this._target),
  53161. BABYLON.Action._GetTargetProperty(this._parent),
  53162. ]
  53163. }, parent);
  53164. };
  53165. return SetParentAction;
  53166. }(BABYLON.Action));
  53167. BABYLON.SetParentAction = SetParentAction;
  53168. var PlaySoundAction = /** @class */ (function (_super) {
  53169. __extends(PlaySoundAction, _super);
  53170. function PlaySoundAction(triggerOptions, sound, condition) {
  53171. var _this = _super.call(this, triggerOptions, condition) || this;
  53172. _this._sound = sound;
  53173. return _this;
  53174. }
  53175. PlaySoundAction.prototype._prepare = function () {
  53176. };
  53177. PlaySoundAction.prototype.execute = function () {
  53178. if (this._sound !== undefined)
  53179. this._sound.play();
  53180. };
  53181. PlaySoundAction.prototype.serialize = function (parent) {
  53182. return _super.prototype._serialize.call(this, {
  53183. name: "PlaySoundAction",
  53184. properties: [{ name: "sound", value: this._sound.name }]
  53185. }, parent);
  53186. };
  53187. return PlaySoundAction;
  53188. }(BABYLON.Action));
  53189. BABYLON.PlaySoundAction = PlaySoundAction;
  53190. var StopSoundAction = /** @class */ (function (_super) {
  53191. __extends(StopSoundAction, _super);
  53192. function StopSoundAction(triggerOptions, sound, condition) {
  53193. var _this = _super.call(this, triggerOptions, condition) || this;
  53194. _this._sound = sound;
  53195. return _this;
  53196. }
  53197. StopSoundAction.prototype._prepare = function () {
  53198. };
  53199. StopSoundAction.prototype.execute = function () {
  53200. if (this._sound !== undefined)
  53201. this._sound.stop();
  53202. };
  53203. StopSoundAction.prototype.serialize = function (parent) {
  53204. return _super.prototype._serialize.call(this, {
  53205. name: "StopSoundAction",
  53206. properties: [{ name: "sound", value: this._sound.name }]
  53207. }, parent);
  53208. };
  53209. return StopSoundAction;
  53210. }(BABYLON.Action));
  53211. BABYLON.StopSoundAction = StopSoundAction;
  53212. })(BABYLON || (BABYLON = {}));
  53213. //# sourceMappingURL=babylon.directActions.js.map
  53214. "use strict";
  53215. var BABYLON;
  53216. (function (BABYLON) {
  53217. var SpriteManager = /** @class */ (function () {
  53218. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53219. if (epsilon === void 0) { epsilon = 0.01; }
  53220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53221. this.name = name;
  53222. this.sprites = new Array();
  53223. this.renderingGroupId = 0;
  53224. this.layerMask = 0x0FFFFFFF;
  53225. this.fogEnabled = true;
  53226. this.isPickable = false;
  53227. /**
  53228. * An event triggered when the manager is disposed.
  53229. */
  53230. this.onDisposeObservable = new BABYLON.Observable();
  53231. this._vertexBuffers = {};
  53232. this._capacity = capacity;
  53233. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53234. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53235. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53236. if (cellSize.width && cellSize.height) {
  53237. this.cellWidth = cellSize.width;
  53238. this.cellHeight = cellSize.height;
  53239. }
  53240. else if (cellSize !== undefined) {
  53241. this.cellWidth = cellSize;
  53242. this.cellHeight = cellSize;
  53243. }
  53244. else {
  53245. return;
  53246. }
  53247. this._epsilon = epsilon;
  53248. this._scene = scene;
  53249. this._scene.spriteManagers.push(this);
  53250. var indices = [];
  53251. var index = 0;
  53252. for (var count = 0; count < capacity; count++) {
  53253. indices.push(index);
  53254. indices.push(index + 1);
  53255. indices.push(index + 2);
  53256. indices.push(index);
  53257. indices.push(index + 2);
  53258. indices.push(index + 3);
  53259. index += 4;
  53260. }
  53261. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53262. // VBO
  53263. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53264. this._vertexData = new Float32Array(capacity * 16 * 4);
  53265. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53266. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53267. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53268. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53269. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53271. this._vertexBuffers["options"] = options;
  53272. this._vertexBuffers["cellInfo"] = cellInfo;
  53273. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53274. // Effects
  53275. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53276. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53277. }
  53278. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53279. set: function (callback) {
  53280. if (this._onDisposeObserver) {
  53281. this.onDisposeObservable.remove(this._onDisposeObserver);
  53282. }
  53283. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53284. },
  53285. enumerable: true,
  53286. configurable: true
  53287. });
  53288. Object.defineProperty(SpriteManager.prototype, "texture", {
  53289. get: function () {
  53290. return this._spriteTexture;
  53291. },
  53292. set: function (value) {
  53293. this._spriteTexture = value;
  53294. },
  53295. enumerable: true,
  53296. configurable: true
  53297. });
  53298. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53299. var arrayOffset = index * 16;
  53300. if (offsetX === 0)
  53301. offsetX = this._epsilon;
  53302. else if (offsetX === 1)
  53303. offsetX = 1 - this._epsilon;
  53304. if (offsetY === 0)
  53305. offsetY = this._epsilon;
  53306. else if (offsetY === 1)
  53307. offsetY = 1 - this._epsilon;
  53308. this._vertexData[arrayOffset] = sprite.position.x;
  53309. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53310. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53311. this._vertexData[arrayOffset + 3] = sprite.angle;
  53312. this._vertexData[arrayOffset + 4] = sprite.width;
  53313. this._vertexData[arrayOffset + 5] = sprite.height;
  53314. this._vertexData[arrayOffset + 6] = offsetX;
  53315. this._vertexData[arrayOffset + 7] = offsetY;
  53316. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53317. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53318. var offset = (sprite.cellIndex / rowSize) >> 0;
  53319. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53320. this._vertexData[arrayOffset + 11] = offset;
  53321. // Color
  53322. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53323. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53324. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53325. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53326. };
  53327. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53328. var count = Math.min(this._capacity, this.sprites.length);
  53329. var min = BABYLON.Vector3.Zero();
  53330. var max = BABYLON.Vector3.Zero();
  53331. var distance = Number.MAX_VALUE;
  53332. var currentSprite = null;
  53333. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53334. var cameraView = camera.getViewMatrix();
  53335. for (var index = 0; index < count; index++) {
  53336. var sprite = this.sprites[index];
  53337. if (!sprite) {
  53338. continue;
  53339. }
  53340. if (predicate) {
  53341. if (!predicate(sprite)) {
  53342. continue;
  53343. }
  53344. }
  53345. else if (!sprite.isPickable) {
  53346. continue;
  53347. }
  53348. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53349. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53350. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53351. if (ray.intersectsBoxMinMax(min, max)) {
  53352. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53353. if (distance > currentDistance) {
  53354. distance = currentDistance;
  53355. currentSprite = sprite;
  53356. if (fastCheck) {
  53357. break;
  53358. }
  53359. }
  53360. }
  53361. }
  53362. if (currentSprite) {
  53363. var result = new BABYLON.PickingInfo();
  53364. result.hit = true;
  53365. result.pickedSprite = currentSprite;
  53366. result.distance = distance;
  53367. return result;
  53368. }
  53369. return null;
  53370. };
  53371. SpriteManager.prototype.render = function () {
  53372. // Check
  53373. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53374. return;
  53375. var engine = this._scene.getEngine();
  53376. var baseSize = this._spriteTexture.getBaseSize();
  53377. // Sprites
  53378. var deltaTime = engine.getDeltaTime();
  53379. var max = Math.min(this._capacity, this.sprites.length);
  53380. var rowSize = baseSize.width / this.cellWidth;
  53381. var offset = 0;
  53382. for (var index = 0; index < max; index++) {
  53383. var sprite = this.sprites[index];
  53384. if (!sprite) {
  53385. continue;
  53386. }
  53387. sprite._animate(deltaTime);
  53388. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53389. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53390. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53391. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53392. }
  53393. this._buffer.update(this._vertexData);
  53394. // Render
  53395. var effect = this._effectBase;
  53396. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53397. effect = this._effectFog;
  53398. }
  53399. engine.enableEffect(effect);
  53400. var viewMatrix = this._scene.getViewMatrix();
  53401. effect.setTexture("diffuseSampler", this._spriteTexture);
  53402. effect.setMatrix("view", viewMatrix);
  53403. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53404. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53405. // Fog
  53406. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53407. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53408. effect.setColor3("vFogColor", this._scene.fogColor);
  53409. }
  53410. // VBOs
  53411. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53412. // Draw order
  53413. engine.setDepthFunctionToLessOrEqual();
  53414. effect.setBool("alphaTest", true);
  53415. engine.setColorWrite(false);
  53416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53417. engine.setColorWrite(true);
  53418. effect.setBool("alphaTest", false);
  53419. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53420. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53421. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53422. };
  53423. SpriteManager.prototype.dispose = function () {
  53424. if (this._buffer) {
  53425. this._buffer.dispose();
  53426. this._buffer = null;
  53427. }
  53428. if (this._indexBuffer) {
  53429. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53430. this._indexBuffer = null;
  53431. }
  53432. if (this._spriteTexture) {
  53433. this._spriteTexture.dispose();
  53434. this._spriteTexture = null;
  53435. }
  53436. // Remove from scene
  53437. var index = this._scene.spriteManagers.indexOf(this);
  53438. this._scene.spriteManagers.splice(index, 1);
  53439. // Callback
  53440. this.onDisposeObservable.notifyObservers(this);
  53441. this.onDisposeObservable.clear();
  53442. };
  53443. return SpriteManager;
  53444. }());
  53445. BABYLON.SpriteManager = SpriteManager;
  53446. })(BABYLON || (BABYLON = {}));
  53447. //# sourceMappingURL=babylon.spriteManager.js.map
  53448. "use strict";
  53449. var BABYLON;
  53450. (function (BABYLON) {
  53451. var Sprite = /** @class */ (function () {
  53452. function Sprite(name, manager) {
  53453. this.name = name;
  53454. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53455. this.width = 1.0;
  53456. this.height = 1.0;
  53457. this.angle = 0;
  53458. this.cellIndex = 0;
  53459. this.invertU = 0;
  53460. this.invertV = 0;
  53461. this.animations = new Array();
  53462. this.isPickable = false;
  53463. this._animationStarted = false;
  53464. this._loopAnimation = false;
  53465. this._fromIndex = 0;
  53466. this._toIndex = 0;
  53467. this._delay = 0;
  53468. this._direction = 1;
  53469. this._time = 0;
  53470. this._manager = manager;
  53471. this._manager.sprites.push(this);
  53472. this.position = BABYLON.Vector3.Zero();
  53473. }
  53474. Object.defineProperty(Sprite.prototype, "size", {
  53475. get: function () {
  53476. return this.width;
  53477. },
  53478. set: function (value) {
  53479. this.width = value;
  53480. this.height = value;
  53481. },
  53482. enumerable: true,
  53483. configurable: true
  53484. });
  53485. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53486. this._fromIndex = from;
  53487. this._toIndex = to;
  53488. this._loopAnimation = loop;
  53489. this._delay = delay;
  53490. this._animationStarted = true;
  53491. this._direction = from < to ? 1 : -1;
  53492. this.cellIndex = from;
  53493. this._time = 0;
  53494. this._onAnimationEnd = onAnimationEnd;
  53495. };
  53496. Sprite.prototype.stopAnimation = function () {
  53497. this._animationStarted = false;
  53498. };
  53499. Sprite.prototype._animate = function (deltaTime) {
  53500. if (!this._animationStarted)
  53501. return;
  53502. this._time += deltaTime;
  53503. if (this._time > this._delay) {
  53504. this._time = this._time % this._delay;
  53505. this.cellIndex += this._direction;
  53506. if (this.cellIndex > this._toIndex) {
  53507. if (this._loopAnimation) {
  53508. this.cellIndex = this._fromIndex;
  53509. }
  53510. else {
  53511. this.cellIndex = this._toIndex;
  53512. this._animationStarted = false;
  53513. if (this._onAnimationEnd) {
  53514. this._onAnimationEnd();
  53515. }
  53516. if (this.disposeWhenFinishedAnimating) {
  53517. this.dispose();
  53518. }
  53519. }
  53520. }
  53521. }
  53522. };
  53523. Sprite.prototype.dispose = function () {
  53524. for (var i = 0; i < this._manager.sprites.length; i++) {
  53525. if (this._manager.sprites[i] == this) {
  53526. this._manager.sprites.splice(i, 1);
  53527. }
  53528. }
  53529. };
  53530. return Sprite;
  53531. }());
  53532. BABYLON.Sprite = Sprite;
  53533. })(BABYLON || (BABYLON = {}));
  53534. //# sourceMappingURL=babylon.sprite.js.map
  53535. "use strict";
  53536. var BABYLON;
  53537. (function (BABYLON) {
  53538. var IntersectionInfo = /** @class */ (function () {
  53539. function IntersectionInfo(bu, bv, distance) {
  53540. this.bu = bu;
  53541. this.bv = bv;
  53542. this.distance = distance;
  53543. this.faceId = 0;
  53544. this.subMeshId = 0;
  53545. }
  53546. return IntersectionInfo;
  53547. }());
  53548. BABYLON.IntersectionInfo = IntersectionInfo;
  53549. var PickingInfo = /** @class */ (function () {
  53550. function PickingInfo() {
  53551. this.hit = false;
  53552. this.distance = 0;
  53553. this.pickedPoint = null;
  53554. this.pickedMesh = null;
  53555. this.bu = 0;
  53556. this.bv = 0;
  53557. this.faceId = -1;
  53558. this.subMeshId = 0;
  53559. this.pickedSprite = null;
  53560. }
  53561. // Methods
  53562. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53563. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53564. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53565. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53566. return null;
  53567. }
  53568. var indices = this.pickedMesh.getIndices();
  53569. if (!indices) {
  53570. return null;
  53571. }
  53572. var result;
  53573. if (useVerticesNormals) {
  53574. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53575. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53576. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53577. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53578. normal0 = normal0.scale(this.bu);
  53579. normal1 = normal1.scale(this.bv);
  53580. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53581. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53582. }
  53583. else {
  53584. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53585. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53586. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53587. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53588. var p1p2 = vertex1.subtract(vertex2);
  53589. var p3p2 = vertex3.subtract(vertex2);
  53590. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53591. }
  53592. if (useWorldCoordinates) {
  53593. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53594. }
  53595. return BABYLON.Vector3.Normalize(result);
  53596. };
  53597. PickingInfo.prototype.getTextureCoordinates = function () {
  53598. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53599. return null;
  53600. }
  53601. var indices = this.pickedMesh.getIndices();
  53602. if (!indices) {
  53603. return null;
  53604. }
  53605. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53606. if (!uvs) {
  53607. return null;
  53608. }
  53609. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53610. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53611. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53612. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53613. uv1 = uv1.scale(this.bu);
  53614. uv2 = uv2.scale(this.bv);
  53615. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53616. };
  53617. return PickingInfo;
  53618. }());
  53619. BABYLON.PickingInfo = PickingInfo;
  53620. })(BABYLON || (BABYLON = {}));
  53621. //# sourceMappingURL=babylon.pickingInfo.js.map
  53622. "use strict";
  53623. var BABYLON;
  53624. (function (BABYLON) {
  53625. var Ray = /** @class */ (function () {
  53626. function Ray(origin, direction, length) {
  53627. if (length === void 0) { length = Number.MAX_VALUE; }
  53628. this.origin = origin;
  53629. this.direction = direction;
  53630. this.length = length;
  53631. }
  53632. // Methods
  53633. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53634. var d = 0.0;
  53635. var maxValue = Number.MAX_VALUE;
  53636. var inv;
  53637. var min;
  53638. var max;
  53639. var temp;
  53640. if (Math.abs(this.direction.x) < 0.0000001) {
  53641. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53642. return false;
  53643. }
  53644. }
  53645. else {
  53646. inv = 1.0 / this.direction.x;
  53647. min = (minimum.x - this.origin.x) * inv;
  53648. max = (maximum.x - this.origin.x) * inv;
  53649. if (max === -Infinity) {
  53650. max = Infinity;
  53651. }
  53652. if (min > max) {
  53653. temp = min;
  53654. min = max;
  53655. max = temp;
  53656. }
  53657. d = Math.max(min, d);
  53658. maxValue = Math.min(max, maxValue);
  53659. if (d > maxValue) {
  53660. return false;
  53661. }
  53662. }
  53663. if (Math.abs(this.direction.y) < 0.0000001) {
  53664. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53665. return false;
  53666. }
  53667. }
  53668. else {
  53669. inv = 1.0 / this.direction.y;
  53670. min = (minimum.y - this.origin.y) * inv;
  53671. max = (maximum.y - this.origin.y) * inv;
  53672. if (max === -Infinity) {
  53673. max = Infinity;
  53674. }
  53675. if (min > max) {
  53676. temp = min;
  53677. min = max;
  53678. max = temp;
  53679. }
  53680. d = Math.max(min, d);
  53681. maxValue = Math.min(max, maxValue);
  53682. if (d > maxValue) {
  53683. return false;
  53684. }
  53685. }
  53686. if (Math.abs(this.direction.z) < 0.0000001) {
  53687. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53688. return false;
  53689. }
  53690. }
  53691. else {
  53692. inv = 1.0 / this.direction.z;
  53693. min = (minimum.z - this.origin.z) * inv;
  53694. max = (maximum.z - this.origin.z) * inv;
  53695. if (max === -Infinity) {
  53696. max = Infinity;
  53697. }
  53698. if (min > max) {
  53699. temp = min;
  53700. min = max;
  53701. max = temp;
  53702. }
  53703. d = Math.max(min, d);
  53704. maxValue = Math.min(max, maxValue);
  53705. if (d > maxValue) {
  53706. return false;
  53707. }
  53708. }
  53709. return true;
  53710. };
  53711. Ray.prototype.intersectsBox = function (box) {
  53712. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53713. };
  53714. Ray.prototype.intersectsSphere = function (sphere) {
  53715. var x = sphere.center.x - this.origin.x;
  53716. var y = sphere.center.y - this.origin.y;
  53717. var z = sphere.center.z - this.origin.z;
  53718. var pyth = (x * x) + (y * y) + (z * z);
  53719. var rr = sphere.radius * sphere.radius;
  53720. if (pyth <= rr) {
  53721. return true;
  53722. }
  53723. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53724. if (dot < 0.0) {
  53725. return false;
  53726. }
  53727. var temp = pyth - (dot * dot);
  53728. return temp <= rr;
  53729. };
  53730. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53731. if (!this._edge1) {
  53732. this._edge1 = BABYLON.Vector3.Zero();
  53733. this._edge2 = BABYLON.Vector3.Zero();
  53734. this._pvec = BABYLON.Vector3.Zero();
  53735. this._tvec = BABYLON.Vector3.Zero();
  53736. this._qvec = BABYLON.Vector3.Zero();
  53737. }
  53738. vertex1.subtractToRef(vertex0, this._edge1);
  53739. vertex2.subtractToRef(vertex0, this._edge2);
  53740. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53741. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53742. if (det === 0) {
  53743. return null;
  53744. }
  53745. var invdet = 1 / det;
  53746. this.origin.subtractToRef(vertex0, this._tvec);
  53747. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53748. if (bu < 0 || bu > 1.0) {
  53749. return null;
  53750. }
  53751. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53752. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53753. if (bv < 0 || bu + bv > 1.0) {
  53754. return null;
  53755. }
  53756. //check if the distance is longer than the predefined length.
  53757. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53758. if (distance > this.length) {
  53759. return null;
  53760. }
  53761. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53762. };
  53763. Ray.prototype.intersectsPlane = function (plane) {
  53764. var distance;
  53765. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53766. if (Math.abs(result1) < 9.99999997475243E-07) {
  53767. return null;
  53768. }
  53769. else {
  53770. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53771. distance = (-plane.d - result2) / result1;
  53772. if (distance < 0.0) {
  53773. if (distance < -9.99999997475243E-07) {
  53774. return null;
  53775. }
  53776. else {
  53777. return 0;
  53778. }
  53779. }
  53780. return distance;
  53781. }
  53782. };
  53783. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53784. var tm = BABYLON.Tmp.Matrix[0];
  53785. mesh.getWorldMatrix().invertToRef(tm);
  53786. if (this._tmpRay) {
  53787. Ray.TransformToRef(this, tm, this._tmpRay);
  53788. }
  53789. else {
  53790. this._tmpRay = Ray.Transform(this, tm);
  53791. }
  53792. return mesh.intersects(this._tmpRay, fastCheck);
  53793. };
  53794. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53795. if (results) {
  53796. results.length = 0;
  53797. }
  53798. else {
  53799. results = [];
  53800. }
  53801. for (var i = 0; i < meshes.length; i++) {
  53802. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53803. if (pickInfo.hit) {
  53804. results.push(pickInfo);
  53805. }
  53806. }
  53807. results.sort(this._comparePickingInfo);
  53808. return results;
  53809. };
  53810. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53811. if (pickingInfoA.distance < pickingInfoB.distance) {
  53812. return -1;
  53813. }
  53814. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53815. return 1;
  53816. }
  53817. else {
  53818. return 0;
  53819. }
  53820. };
  53821. /**
  53822. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53823. * @param sega the first point of the segment to test the intersection against
  53824. * @param segb the second point of the segment to test the intersection against
  53825. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53826. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53827. */
  53828. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53829. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53830. var u = segb.subtract(sega);
  53831. var v = rsegb.subtract(this.origin);
  53832. var w = sega.subtract(this.origin);
  53833. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53834. var b = BABYLON.Vector3.Dot(u, v);
  53835. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53836. var d = BABYLON.Vector3.Dot(u, w);
  53837. var e = BABYLON.Vector3.Dot(v, w);
  53838. var D = a * c - b * b; // always >= 0
  53839. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53840. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53841. // compute the line parameters of the two closest points
  53842. if (D < Ray.smallnum) {
  53843. sN = 0.0; // force using point P0 on segment S1
  53844. sD = 1.0; // to prevent possible division by 0.0 later
  53845. tN = e;
  53846. tD = c;
  53847. }
  53848. else {
  53849. sN = (b * e - c * d);
  53850. tN = (a * e - b * d);
  53851. if (sN < 0.0) {
  53852. sN = 0.0;
  53853. tN = e;
  53854. tD = c;
  53855. }
  53856. else if (sN > sD) {
  53857. sN = sD;
  53858. tN = e + b;
  53859. tD = c;
  53860. }
  53861. }
  53862. if (tN < 0.0) {
  53863. tN = 0.0;
  53864. // recompute sc for this edge
  53865. if (-d < 0.0) {
  53866. sN = 0.0;
  53867. }
  53868. else if (-d > a)
  53869. sN = sD;
  53870. else {
  53871. sN = -d;
  53872. sD = a;
  53873. }
  53874. }
  53875. else if (tN > tD) {
  53876. tN = tD;
  53877. // recompute sc for this edge
  53878. if ((-d + b) < 0.0) {
  53879. sN = 0;
  53880. }
  53881. else if ((-d + b) > a) {
  53882. sN = sD;
  53883. }
  53884. else {
  53885. sN = (-d + b);
  53886. sD = a;
  53887. }
  53888. }
  53889. // finally do the division to get sc and tc
  53890. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53891. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53892. // get the difference of the two closest points
  53893. var qtc = v.multiplyByFloats(tc, tc, tc);
  53894. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53895. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53896. if (isIntersected) {
  53897. return qtc.length();
  53898. }
  53899. return -1;
  53900. };
  53901. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53902. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53903. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53904. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53905. this.direction.normalize();
  53906. return this;
  53907. };
  53908. // Statics
  53909. Ray.Zero = function () {
  53910. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53911. };
  53912. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53913. var result = Ray.Zero();
  53914. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53915. };
  53916. /**
  53917. * 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
  53918. * transformed to the given world matrix.
  53919. * @param origin The origin point
  53920. * @param end The end point
  53921. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53922. */
  53923. Ray.CreateNewFromTo = function (origin, end, world) {
  53924. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53925. var direction = end.subtract(origin);
  53926. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53927. direction.normalize();
  53928. return Ray.Transform(new Ray(origin, direction, length), world);
  53929. };
  53930. Ray.Transform = function (ray, matrix) {
  53931. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53932. Ray.TransformToRef(ray, matrix, result);
  53933. return result;
  53934. };
  53935. Ray.TransformToRef = function (ray, matrix, result) {
  53936. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53937. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53938. result.length = ray.length;
  53939. var dir = result.direction;
  53940. var len = dir.length();
  53941. if (!(len === 0 || len === 1)) {
  53942. var num = 1.0 / len;
  53943. dir.x *= num;
  53944. dir.y *= num;
  53945. dir.z *= num;
  53946. result.length *= len;
  53947. }
  53948. };
  53949. Ray.smallnum = 0.00000001;
  53950. Ray.rayl = 10e8;
  53951. return Ray;
  53952. }());
  53953. BABYLON.Ray = Ray;
  53954. })(BABYLON || (BABYLON = {}));
  53955. //# sourceMappingURL=babylon.ray.js.map
  53956. "use strict";
  53957. var BABYLON;
  53958. (function (BABYLON) {
  53959. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53960. if (boxMin.x > sphereCenter.x + sphereRadius)
  53961. return false;
  53962. if (sphereCenter.x - sphereRadius > boxMax.x)
  53963. return false;
  53964. if (boxMin.y > sphereCenter.y + sphereRadius)
  53965. return false;
  53966. if (sphereCenter.y - sphereRadius > boxMax.y)
  53967. return false;
  53968. if (boxMin.z > sphereCenter.z + sphereRadius)
  53969. return false;
  53970. if (sphereCenter.z - sphereRadius > boxMax.z)
  53971. return false;
  53972. return true;
  53973. };
  53974. var getLowestRoot = (function () {
  53975. var result = { root: 0, found: false };
  53976. return function (a, b, c, maxR) {
  53977. result.root = 0;
  53978. result.found = false;
  53979. var determinant = b * b - 4.0 * a * c;
  53980. if (determinant < 0)
  53981. return result;
  53982. var sqrtD = Math.sqrt(determinant);
  53983. var r1 = (-b - sqrtD) / (2.0 * a);
  53984. var r2 = (-b + sqrtD) / (2.0 * a);
  53985. if (r1 > r2) {
  53986. var temp = r2;
  53987. r2 = r1;
  53988. r1 = temp;
  53989. }
  53990. if (r1 > 0 && r1 < maxR) {
  53991. result.root = r1;
  53992. result.found = true;
  53993. return result;
  53994. }
  53995. if (r2 > 0 && r2 < maxR) {
  53996. result.root = r2;
  53997. result.found = true;
  53998. return result;
  53999. }
  54000. return result;
  54001. };
  54002. })();
  54003. var Collider = /** @class */ (function () {
  54004. function Collider() {
  54005. this._collisionPoint = BABYLON.Vector3.Zero();
  54006. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54007. this._tempVector = BABYLON.Vector3.Zero();
  54008. this._tempVector2 = BABYLON.Vector3.Zero();
  54009. this._tempVector3 = BABYLON.Vector3.Zero();
  54010. this._tempVector4 = BABYLON.Vector3.Zero();
  54011. this._edge = BABYLON.Vector3.Zero();
  54012. this._baseToVertex = BABYLON.Vector3.Zero();
  54013. this._destinationPoint = BABYLON.Vector3.Zero();
  54014. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54015. this._displacementVector = BABYLON.Vector3.Zero();
  54016. this._radius = BABYLON.Vector3.One();
  54017. this._retry = 0;
  54018. this._basePointWorld = BABYLON.Vector3.Zero();
  54019. this._velocityWorld = BABYLON.Vector3.Zero();
  54020. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54021. this._collisionMask = -1;
  54022. }
  54023. Object.defineProperty(Collider.prototype, "collisionMask", {
  54024. get: function () {
  54025. return this._collisionMask;
  54026. },
  54027. set: function (mask) {
  54028. this._collisionMask = !isNaN(mask) ? mask : -1;
  54029. },
  54030. enumerable: true,
  54031. configurable: true
  54032. });
  54033. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54034. /**
  54035. * Gets the plane normal used to compute the sliding response (in local space)
  54036. */
  54037. get: function () {
  54038. return this._slidePlaneNormal;
  54039. },
  54040. enumerable: true,
  54041. configurable: true
  54042. });
  54043. // Methods
  54044. Collider.prototype._initialize = function (source, dir, e) {
  54045. this._velocity = dir;
  54046. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54047. this._basePoint = source;
  54048. source.multiplyToRef(this._radius, this._basePointWorld);
  54049. dir.multiplyToRef(this._radius, this._velocityWorld);
  54050. this._velocityWorldLength = this._velocityWorld.length();
  54051. this._epsilon = e;
  54052. this.collisionFound = false;
  54053. };
  54054. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54055. pa.subtractToRef(point, this._tempVector);
  54056. pb.subtractToRef(point, this._tempVector2);
  54057. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54058. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54059. if (d < 0)
  54060. return false;
  54061. pc.subtractToRef(point, this._tempVector3);
  54062. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54063. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54064. if (d < 0)
  54065. return false;
  54066. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54067. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54068. return d >= 0;
  54069. };
  54070. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54071. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54072. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54073. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54074. return false;
  54075. }
  54076. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54077. return false;
  54078. return true;
  54079. };
  54080. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54081. var t0;
  54082. var embeddedInPlane = false;
  54083. //defensive programming, actually not needed.
  54084. if (!trianglePlaneArray) {
  54085. trianglePlaneArray = [];
  54086. }
  54087. if (!trianglePlaneArray[faceIndex]) {
  54088. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54089. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54090. }
  54091. var trianglePlane = trianglePlaneArray[faceIndex];
  54092. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54093. return;
  54094. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54095. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54096. if (normalDotVelocity == 0) {
  54097. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54098. return;
  54099. embeddedInPlane = true;
  54100. t0 = 0;
  54101. }
  54102. else {
  54103. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54104. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54105. if (t0 > t1) {
  54106. var temp = t1;
  54107. t1 = t0;
  54108. t0 = temp;
  54109. }
  54110. if (t0 > 1.0 || t1 < 0.0)
  54111. return;
  54112. if (t0 < 0)
  54113. t0 = 0;
  54114. if (t0 > 1.0)
  54115. t0 = 1.0;
  54116. }
  54117. this._collisionPoint.copyFromFloats(0, 0, 0);
  54118. var found = false;
  54119. var t = 1.0;
  54120. if (!embeddedInPlane) {
  54121. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54122. this._velocity.scaleToRef(t0, this._tempVector);
  54123. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54124. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54125. found = true;
  54126. t = t0;
  54127. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54128. }
  54129. }
  54130. if (!found) {
  54131. var velocitySquaredLength = this._velocity.lengthSquared();
  54132. var a = velocitySquaredLength;
  54133. this._basePoint.subtractToRef(p1, this._tempVector);
  54134. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54135. var c = this._tempVector.lengthSquared() - 1.0;
  54136. var lowestRoot = getLowestRoot(a, b, c, t);
  54137. if (lowestRoot.found) {
  54138. t = lowestRoot.root;
  54139. found = true;
  54140. this._collisionPoint.copyFrom(p1);
  54141. }
  54142. this._basePoint.subtractToRef(p2, this._tempVector);
  54143. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54144. c = this._tempVector.lengthSquared() - 1.0;
  54145. lowestRoot = getLowestRoot(a, b, c, t);
  54146. if (lowestRoot.found) {
  54147. t = lowestRoot.root;
  54148. found = true;
  54149. this._collisionPoint.copyFrom(p2);
  54150. }
  54151. this._basePoint.subtractToRef(p3, this._tempVector);
  54152. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54153. c = this._tempVector.lengthSquared() - 1.0;
  54154. lowestRoot = getLowestRoot(a, b, c, t);
  54155. if (lowestRoot.found) {
  54156. t = lowestRoot.root;
  54157. found = true;
  54158. this._collisionPoint.copyFrom(p3);
  54159. }
  54160. p2.subtractToRef(p1, this._edge);
  54161. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54162. var edgeSquaredLength = this._edge.lengthSquared();
  54163. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54164. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54165. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54166. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54167. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54168. lowestRoot = getLowestRoot(a, b, c, t);
  54169. if (lowestRoot.found) {
  54170. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54171. if (f >= 0.0 && f <= 1.0) {
  54172. t = lowestRoot.root;
  54173. found = true;
  54174. this._edge.scaleInPlace(f);
  54175. p1.addToRef(this._edge, this._collisionPoint);
  54176. }
  54177. }
  54178. p3.subtractToRef(p2, this._edge);
  54179. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54180. edgeSquaredLength = this._edge.lengthSquared();
  54181. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54182. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54183. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54184. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54185. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54186. lowestRoot = getLowestRoot(a, b, c, t);
  54187. if (lowestRoot.found) {
  54188. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54189. if (f >= 0.0 && f <= 1.0) {
  54190. t = lowestRoot.root;
  54191. found = true;
  54192. this._edge.scaleInPlace(f);
  54193. p2.addToRef(this._edge, this._collisionPoint);
  54194. }
  54195. }
  54196. p1.subtractToRef(p3, this._edge);
  54197. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54198. edgeSquaredLength = this._edge.lengthSquared();
  54199. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54200. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54201. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54202. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54203. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54204. lowestRoot = getLowestRoot(a, b, c, t);
  54205. if (lowestRoot.found) {
  54206. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54207. if (f >= 0.0 && f <= 1.0) {
  54208. t = lowestRoot.root;
  54209. found = true;
  54210. this._edge.scaleInPlace(f);
  54211. p3.addToRef(this._edge, this._collisionPoint);
  54212. }
  54213. }
  54214. }
  54215. if (found) {
  54216. var distToCollision = t * this._velocity.length();
  54217. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54218. if (!this.intersectionPoint) {
  54219. this.intersectionPoint = this._collisionPoint.clone();
  54220. }
  54221. else {
  54222. this.intersectionPoint.copyFrom(this._collisionPoint);
  54223. }
  54224. this._nearestDistance = distToCollision;
  54225. this.collisionFound = true;
  54226. }
  54227. }
  54228. };
  54229. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54230. for (var i = indexStart; i < indexEnd; i += 3) {
  54231. var p1 = pts[indices[i] - decal];
  54232. var p2 = pts[indices[i + 1] - decal];
  54233. var p3 = pts[indices[i + 2] - decal];
  54234. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54235. }
  54236. };
  54237. Collider.prototype._getResponse = function (pos, vel) {
  54238. pos.addToRef(vel, this._destinationPoint);
  54239. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54240. this._basePoint.addToRef(vel, pos);
  54241. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54242. this._slidePlaneNormal.normalize();
  54243. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54244. pos.addInPlace(this._displacementVector);
  54245. this.intersectionPoint.addInPlace(this._displacementVector);
  54246. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54247. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54248. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54249. };
  54250. return Collider;
  54251. }());
  54252. BABYLON.Collider = Collider;
  54253. })(BABYLON || (BABYLON = {}));
  54254. //# sourceMappingURL=babylon.collider.js.map
  54255. "use strict";
  54256. var BABYLON;
  54257. (function (BABYLON) {
  54258. //WebWorker code will be inserted to this variable.
  54259. BABYLON.CollisionWorker = "";
  54260. var WorkerTaskType;
  54261. (function (WorkerTaskType) {
  54262. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54263. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54264. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54265. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54266. var WorkerReplyType;
  54267. (function (WorkerReplyType) {
  54268. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54269. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54270. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54271. var CollisionCoordinatorWorker = /** @class */ (function () {
  54272. function CollisionCoordinatorWorker() {
  54273. var _this = this;
  54274. this._scaledPosition = BABYLON.Vector3.Zero();
  54275. this._scaledVelocity = BABYLON.Vector3.Zero();
  54276. this.onMeshUpdated = function (transformNode) {
  54277. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54278. };
  54279. this.onGeometryUpdated = function (geometry) {
  54280. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54281. };
  54282. this._afterRender = function () {
  54283. if (!_this._init)
  54284. return;
  54285. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54286. return;
  54287. }
  54288. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54289. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54290. if (_this._runningUpdated > 4) {
  54291. return;
  54292. }
  54293. ++_this._runningUpdated;
  54294. var payload = {
  54295. updatedMeshes: _this._addUpdateMeshesList,
  54296. updatedGeometries: _this._addUpdateGeometriesList,
  54297. removedGeometries: _this._toRemoveGeometryArray,
  54298. removedMeshes: _this._toRemoveMeshesArray
  54299. };
  54300. var message = {
  54301. payload: payload,
  54302. taskType: WorkerTaskType.UPDATE
  54303. };
  54304. var serializable = [];
  54305. for (var id in payload.updatedGeometries) {
  54306. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54307. //prepare transferables
  54308. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54309. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54310. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54311. }
  54312. }
  54313. _this._worker.postMessage(message, serializable);
  54314. _this._addUpdateMeshesList = {};
  54315. _this._addUpdateGeometriesList = {};
  54316. _this._toRemoveGeometryArray = [];
  54317. _this._toRemoveMeshesArray = [];
  54318. };
  54319. this._onMessageFromWorker = function (e) {
  54320. var returnData = e.data;
  54321. if (returnData.error != WorkerReplyType.SUCCESS) {
  54322. //TODO what errors can be returned from the worker?
  54323. BABYLON.Tools.Warn("error returned from worker!");
  54324. return;
  54325. }
  54326. switch (returnData.taskType) {
  54327. case WorkerTaskType.INIT:
  54328. _this._init = true;
  54329. //Update the worked with ALL of the scene's current state
  54330. _this._scene.meshes.forEach(function (mesh) {
  54331. _this.onMeshAdded(mesh);
  54332. });
  54333. _this._scene.getGeometries().forEach(function (geometry) {
  54334. _this.onGeometryAdded(geometry);
  54335. });
  54336. break;
  54337. case WorkerTaskType.UPDATE:
  54338. _this._runningUpdated--;
  54339. break;
  54340. case WorkerTaskType.COLLIDE:
  54341. var returnPayload = returnData.payload;
  54342. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54343. return;
  54344. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54345. if (callback) {
  54346. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54347. if (mesh) {
  54348. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54349. }
  54350. }
  54351. //cleanup
  54352. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54353. break;
  54354. }
  54355. };
  54356. this._collisionsCallbackArray = [];
  54357. this._init = false;
  54358. this._runningUpdated = 0;
  54359. this._addUpdateMeshesList = {};
  54360. this._addUpdateGeometriesList = {};
  54361. this._toRemoveGeometryArray = [];
  54362. this._toRemoveMeshesArray = [];
  54363. }
  54364. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54365. if (!this._init)
  54366. return;
  54367. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54368. return;
  54369. position.divideToRef(collider._radius, this._scaledPosition);
  54370. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54371. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54372. var payload = {
  54373. collider: {
  54374. position: this._scaledPosition.asArray(),
  54375. velocity: this._scaledVelocity.asArray(),
  54376. radius: collider._radius.asArray()
  54377. },
  54378. collisionId: collisionIndex,
  54379. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54380. maximumRetry: maximumRetry
  54381. };
  54382. var message = {
  54383. payload: payload,
  54384. taskType: WorkerTaskType.COLLIDE
  54385. };
  54386. this._worker.postMessage(message);
  54387. };
  54388. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54389. this._scene = scene;
  54390. this._scene.registerAfterRender(this._afterRender);
  54391. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54392. this._worker = new Worker(workerUrl);
  54393. this._worker.onmessage = this._onMessageFromWorker;
  54394. var message = {
  54395. payload: {},
  54396. taskType: WorkerTaskType.INIT
  54397. };
  54398. this._worker.postMessage(message);
  54399. };
  54400. CollisionCoordinatorWorker.prototype.destroy = function () {
  54401. this._scene.unregisterAfterRender(this._afterRender);
  54402. this._worker.terminate();
  54403. };
  54404. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54405. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54406. this.onMeshUpdated(mesh);
  54407. };
  54408. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54409. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54410. };
  54411. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54412. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54413. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54414. this.onGeometryUpdated(geometry);
  54415. };
  54416. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54417. this._toRemoveGeometryArray.push(geometry.id);
  54418. };
  54419. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54420. var submeshes = [];
  54421. if (mesh.subMeshes) {
  54422. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54423. var boundingInfo = sm.getBoundingInfo();
  54424. return {
  54425. position: idx,
  54426. verticesStart: sm.verticesStart,
  54427. verticesCount: sm.verticesCount,
  54428. indexStart: sm.indexStart,
  54429. indexCount: sm.indexCount,
  54430. hasMaterial: !!sm.getMaterial(),
  54431. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54432. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54433. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54434. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54435. };
  54436. });
  54437. }
  54438. var geometryId = null;
  54439. if (mesh instanceof BABYLON.Mesh) {
  54440. var geometry = mesh.geometry;
  54441. geometryId = geometry ? geometry.id : null;
  54442. }
  54443. else if (mesh instanceof BABYLON.InstancedMesh) {
  54444. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54445. geometryId = geometry ? geometry.id : null;
  54446. }
  54447. var boundingInfo = mesh.getBoundingInfo();
  54448. return {
  54449. uniqueId: mesh.uniqueId,
  54450. id: mesh.id,
  54451. name: mesh.name,
  54452. geometryId: geometryId,
  54453. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54454. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54455. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54456. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54457. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54458. subMeshes: submeshes,
  54459. checkCollisions: mesh.checkCollisions
  54460. };
  54461. };
  54462. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54463. return {
  54464. id: geometry.id,
  54465. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54466. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54467. indices: new Uint32Array(geometry.getIndices() || []),
  54468. };
  54469. };
  54470. return CollisionCoordinatorWorker;
  54471. }());
  54472. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54473. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54474. function CollisionCoordinatorLegacy() {
  54475. this._scaledPosition = BABYLON.Vector3.Zero();
  54476. this._scaledVelocity = BABYLON.Vector3.Zero();
  54477. this._finalPosition = BABYLON.Vector3.Zero();
  54478. }
  54479. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54480. position.divideToRef(collider._radius, this._scaledPosition);
  54481. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54482. collider.collidedMesh = null;
  54483. collider._retry = 0;
  54484. collider._initialVelocity = this._scaledVelocity;
  54485. collider._initialPosition = this._scaledPosition;
  54486. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54487. this._finalPosition.multiplyInPlace(collider._radius);
  54488. //run the callback
  54489. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54490. };
  54491. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54492. this._scene = scene;
  54493. };
  54494. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54495. //Legacy need no destruction method.
  54496. };
  54497. //No update in legacy mode
  54498. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54499. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54500. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54501. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54502. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54503. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54504. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54505. if (excludedMesh === void 0) { excludedMesh = null; }
  54506. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54507. if (collider._retry >= maximumRetry) {
  54508. finalPosition.copyFrom(position);
  54509. return;
  54510. }
  54511. // Check if this is a mesh else camera or -1
  54512. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54513. collider._initialize(position, velocity, closeDistance);
  54514. // Check all meshes
  54515. for (var index = 0; index < this._scene.meshes.length; index++) {
  54516. var mesh = this._scene.meshes[index];
  54517. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54518. mesh._checkCollision(collider);
  54519. }
  54520. }
  54521. if (!collider.collisionFound) {
  54522. position.addToRef(velocity, finalPosition);
  54523. return;
  54524. }
  54525. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54526. collider._getResponse(position, velocity);
  54527. }
  54528. if (velocity.length() <= closeDistance) {
  54529. finalPosition.copyFrom(position);
  54530. return;
  54531. }
  54532. collider._retry++;
  54533. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54534. };
  54535. return CollisionCoordinatorLegacy;
  54536. }());
  54537. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54538. })(BABYLON || (BABYLON = {}));
  54539. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54540. "use strict";
  54541. var BABYLON;
  54542. (function (BABYLON) {
  54543. /**
  54544. * A particle represents one of the element emitted by a particle system.
  54545. * This is mainly define by its coordinates, direction, velocity and age.
  54546. */
  54547. var Particle = /** @class */ (function () {
  54548. /**
  54549. * Creates a new instance Particle
  54550. * @param particleSystem the particle system the particle belongs to
  54551. */
  54552. function Particle(
  54553. /**
  54554. * particleSystem the particle system the particle belongs to.
  54555. */
  54556. particleSystem) {
  54557. this.particleSystem = particleSystem;
  54558. /**
  54559. * The world position of the particle in the scene.
  54560. */
  54561. this.position = BABYLON.Vector3.Zero();
  54562. /**
  54563. * The world direction of the particle in the scene.
  54564. */
  54565. this.direction = BABYLON.Vector3.Zero();
  54566. /**
  54567. * The color of the particle.
  54568. */
  54569. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54570. /**
  54571. * The color change of the particle per step.
  54572. */
  54573. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54574. /**
  54575. * Defines how long will the life of the particle be.
  54576. */
  54577. this.lifeTime = 1.0;
  54578. /**
  54579. * The current age of the particle.
  54580. */
  54581. this.age = 0;
  54582. /**
  54583. * The current size of the particle.
  54584. */
  54585. this.size = 0;
  54586. /**
  54587. * The current angle of the particle.
  54588. */
  54589. this.angle = 0;
  54590. /**
  54591. * Defines how fast is the angle changing.
  54592. */
  54593. this.angularSpeed = 0;
  54594. /**
  54595. * Defines the cell index used by the particle to be rendered from a sprite.
  54596. */
  54597. this.cellIndex = 0;
  54598. this._currentFrameCounter = 0;
  54599. if (!this.particleSystem.isAnimationSheetEnabled) {
  54600. return;
  54601. }
  54602. this.updateCellInfoFromSystem();
  54603. }
  54604. Particle.prototype.updateCellInfoFromSystem = function () {
  54605. this.cellIndex = this.particleSystem.startSpriteCellID;
  54606. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54607. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54608. }
  54609. else {
  54610. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54611. }
  54612. };
  54613. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54614. // (ageOffset / scaledUpdateSpeed) / available cells
  54615. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54616. this._currentFrameCounter += scaledUpdateSpeed;
  54617. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54618. this._currentFrameCounter = 0;
  54619. this.cellIndex++;
  54620. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54621. this.cellIndex = this.particleSystem.endSpriteCellID;
  54622. }
  54623. }
  54624. };
  54625. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54626. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54627. this.cellIndex++;
  54628. this._currentFrameCounter = 0;
  54629. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54630. if (this.particleSystem.spriteCellLoop) {
  54631. this.cellIndex = this.particleSystem.startSpriteCellID;
  54632. }
  54633. else {
  54634. this.cellIndex = this.particleSystem.endSpriteCellID;
  54635. }
  54636. }
  54637. }
  54638. else {
  54639. this._currentFrameCounter++;
  54640. }
  54641. };
  54642. /**
  54643. * Copy the properties of particle to another one.
  54644. * @param other the particle to copy the information to.
  54645. */
  54646. Particle.prototype.copyTo = function (other) {
  54647. other.position.copyFrom(this.position);
  54648. other.direction.copyFrom(this.direction);
  54649. other.color.copyFrom(this.color);
  54650. other.colorStep.copyFrom(this.colorStep);
  54651. other.lifeTime = this.lifeTime;
  54652. other.age = this.age;
  54653. other.size = this.size;
  54654. other.angle = this.angle;
  54655. other.angularSpeed = this.angularSpeed;
  54656. other.particleSystem = this.particleSystem;
  54657. other.cellIndex = this.cellIndex;
  54658. };
  54659. return Particle;
  54660. }());
  54661. BABYLON.Particle = Particle;
  54662. })(BABYLON || (BABYLON = {}));
  54663. //# sourceMappingURL=babylon.particle.js.map
  54664. "use strict";
  54665. var BABYLON;
  54666. (function (BABYLON) {
  54667. /**
  54668. * This represents a particle system in Babylon.
  54669. * 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.
  54670. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54671. * @example https://doc.babylonjs.com/babylon101/particles
  54672. */
  54673. var ParticleSystem = /** @class */ (function () {
  54674. /**
  54675. * Instantiates a particle system.
  54676. * 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.
  54677. * @param name The name of the particle system
  54678. * @param capacity The max number of particles alive at the same time
  54679. * @param scene The scene the particle system belongs to
  54680. * @param customEffect a custom effect used to change the way particles are rendered by default
  54681. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54682. * @param epsilon Offset used to render the particles
  54683. */
  54684. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54685. if (customEffect === void 0) { customEffect = null; }
  54686. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54687. if (epsilon === void 0) { epsilon = 0.01; }
  54688. var _this = this;
  54689. /**
  54690. * List of animations used by the particle system.
  54691. */
  54692. this.animations = [];
  54693. /**
  54694. * The rendering group used by the Particle system to chose when to render.
  54695. */
  54696. this.renderingGroupId = 0;
  54697. /**
  54698. * The emitter represents the Mesh or position we are attaching the particle system to.
  54699. */
  54700. this.emitter = null;
  54701. /**
  54702. * The maximum number of particles to emit per frame
  54703. */
  54704. this.emitRate = 10;
  54705. /**
  54706. * If you want to launch only a few particles at once, that can be done, as well.
  54707. */
  54708. this.manualEmitCount = -1;
  54709. /**
  54710. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54711. */
  54712. this.updateSpeed = 0.01;
  54713. /**
  54714. * The amount of time the particle system is running (depends of the overall update speed).
  54715. */
  54716. this.targetStopDuration = 0;
  54717. /**
  54718. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54719. */
  54720. this.disposeOnStop = false;
  54721. /**
  54722. * Minimum power of emitting particles.
  54723. */
  54724. this.minEmitPower = 1;
  54725. /**
  54726. * Maximum power of emitting particles.
  54727. */
  54728. this.maxEmitPower = 1;
  54729. /**
  54730. * Minimum life time of emitting particles.
  54731. */
  54732. this.minLifeTime = 1;
  54733. /**
  54734. * Maximum life time of emitting particles.
  54735. */
  54736. this.maxLifeTime = 1;
  54737. /**
  54738. * Minimum Size of emitting particles.
  54739. */
  54740. this.minSize = 1;
  54741. /**
  54742. * Maximum Size of emitting particles.
  54743. */
  54744. this.maxSize = 1;
  54745. /**
  54746. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54747. */
  54748. this.minAngularSpeed = 0;
  54749. /**
  54750. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54751. */
  54752. this.maxAngularSpeed = 0;
  54753. /**
  54754. * The layer mask we are rendering the particles through.
  54755. */
  54756. this.layerMask = 0x0FFFFFFF;
  54757. /**
  54758. * This can help using your own shader to render the particle system.
  54759. * The according effect will be created
  54760. */
  54761. this.customShader = null;
  54762. /**
  54763. * By default particle system starts as soon as they are created. This prevents the
  54764. * automatic start to happen and let you decide when to start emitting particles.
  54765. */
  54766. this.preventAutoStart = false;
  54767. /**
  54768. * Callback triggered when the particle animation is ending.
  54769. */
  54770. this.onAnimationEnd = null;
  54771. /**
  54772. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54773. */
  54774. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54775. /**
  54776. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54777. * to override the particles.
  54778. */
  54779. this.forceDepthWrite = false;
  54780. /**
  54781. * You can use gravity if you want to give an orientation to your particles.
  54782. */
  54783. this.gravity = BABYLON.Vector3.Zero();
  54784. /**
  54785. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54786. */
  54787. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54788. /**
  54789. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54790. */
  54791. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54792. /**
  54793. * Color the particle will have at the end of its lifetime.
  54794. */
  54795. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54796. /**
  54797. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54798. */
  54799. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54800. /**
  54801. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54802. */
  54803. this.spriteCellLoop = true;
  54804. /**
  54805. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54806. */
  54807. this.spriteCellChangeSpeed = 0;
  54808. /**
  54809. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54810. */
  54811. this.startSpriteCellID = 0;
  54812. /**
  54813. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54814. */
  54815. this.endSpriteCellID = 0;
  54816. /**
  54817. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54818. */
  54819. this.spriteCellWidth = 0;
  54820. /**
  54821. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54822. */
  54823. this.spriteCellHeight = 0;
  54824. /**
  54825. * An event triggered when the system is disposed.
  54826. */
  54827. this.onDisposeObservable = new BABYLON.Observable();
  54828. this._particles = new Array();
  54829. this._stockParticles = new Array();
  54830. this._newPartsExcess = 0;
  54831. this._vertexBuffers = {};
  54832. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54833. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54834. this._scaledDirection = BABYLON.Vector3.Zero();
  54835. this._scaledGravity = BABYLON.Vector3.Zero();
  54836. this._currentRenderId = -1;
  54837. this._started = false;
  54838. this._stopped = false;
  54839. this._actualFrame = 0;
  54840. this._vertexBufferSize = 11;
  54841. // start of sub system methods
  54842. /**
  54843. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54844. * Its lifetime will start back at 0.
  54845. */
  54846. this.recycleParticle = function (particle) {
  54847. var lastParticle = _this._particles.pop();
  54848. if (lastParticle !== particle) {
  54849. lastParticle.copyTo(particle);
  54850. }
  54851. _this._stockParticles.push(lastParticle);
  54852. };
  54853. this._createParticle = function () {
  54854. var particle;
  54855. if (_this._stockParticles.length !== 0) {
  54856. particle = _this._stockParticles.pop();
  54857. particle.age = 0;
  54858. particle.cellIndex = _this.startSpriteCellID;
  54859. }
  54860. else {
  54861. particle = new BABYLON.Particle(_this);
  54862. }
  54863. return particle;
  54864. };
  54865. this._emitFromParticle = function (particle) {
  54866. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54867. return;
  54868. }
  54869. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54870. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54871. subSystem._rootParticleSystem = _this;
  54872. _this.activeSubSystems.push(subSystem);
  54873. subSystem.start();
  54874. };
  54875. this._appendParticleVertexes = null;
  54876. this.id = name;
  54877. this.name = name;
  54878. this._capacity = capacity;
  54879. this._epsilon = epsilon;
  54880. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54881. if (isAnimationSheetEnabled) {
  54882. this._vertexBufferSize = 12;
  54883. }
  54884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54885. this._customEffect = customEffect;
  54886. scene.particleSystems.push(this);
  54887. this._createIndexBuffer();
  54888. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54889. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54890. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54891. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54892. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54893. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54894. if (this._isAnimationSheetEnabled) {
  54895. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54896. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54897. }
  54898. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54899. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54900. this._vertexBuffers["options"] = options;
  54901. // Default emitter type
  54902. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54903. this.updateFunction = function (particles) {
  54904. for (var index = 0; index < particles.length; index++) {
  54905. var particle = particles[index];
  54906. particle.age += _this._scaledUpdateSpeed;
  54907. if (particle.age >= particle.lifeTime) {
  54908. _this._emitFromParticle(particle);
  54909. _this.recycleParticle(particle);
  54910. index--;
  54911. continue;
  54912. }
  54913. else {
  54914. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54915. particle.color.addInPlace(_this._scaledColorStep);
  54916. if (particle.color.a < 0)
  54917. particle.color.a = 0;
  54918. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54919. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54920. particle.position.addInPlace(_this._scaledDirection);
  54921. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54922. particle.direction.addInPlace(_this._scaledGravity);
  54923. if (_this._isAnimationSheetEnabled) {
  54924. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54925. }
  54926. }
  54927. }
  54928. };
  54929. }
  54930. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54931. /**
  54932. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54933. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54934. */
  54935. get: function () {
  54936. if (this.particleEmitterType.direction1) {
  54937. return this.particleEmitterType.direction1;
  54938. }
  54939. return BABYLON.Vector3.Zero();
  54940. },
  54941. set: function (value) {
  54942. if (this.particleEmitterType.direction1) {
  54943. this.particleEmitterType.direction1 = value;
  54944. }
  54945. },
  54946. enumerable: true,
  54947. configurable: true
  54948. });
  54949. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54950. /**
  54951. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54952. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54953. */
  54954. get: function () {
  54955. if (this.particleEmitterType.direction2) {
  54956. return this.particleEmitterType.direction2;
  54957. }
  54958. return BABYLON.Vector3.Zero();
  54959. },
  54960. set: function (value) {
  54961. if (this.particleEmitterType.direction2) {
  54962. this.particleEmitterType.direction2 = value;
  54963. }
  54964. },
  54965. enumerable: true,
  54966. configurable: true
  54967. });
  54968. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54969. /**
  54970. * 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.
  54971. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54972. */
  54973. get: function () {
  54974. if (this.particleEmitterType.minEmitBox) {
  54975. return this.particleEmitterType.minEmitBox;
  54976. }
  54977. return BABYLON.Vector3.Zero();
  54978. },
  54979. set: function (value) {
  54980. if (this.particleEmitterType.minEmitBox) {
  54981. this.particleEmitterType.minEmitBox = value;
  54982. }
  54983. },
  54984. enumerable: true,
  54985. configurable: true
  54986. });
  54987. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54988. /**
  54989. * 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.
  54990. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54991. */
  54992. get: function () {
  54993. if (this.particleEmitterType.maxEmitBox) {
  54994. return this.particleEmitterType.maxEmitBox;
  54995. }
  54996. return BABYLON.Vector3.Zero();
  54997. },
  54998. set: function (value) {
  54999. if (this.particleEmitterType.maxEmitBox) {
  55000. this.particleEmitterType.maxEmitBox = value;
  55001. }
  55002. },
  55003. enumerable: true,
  55004. configurable: true
  55005. });
  55006. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55007. /**
  55008. * Sets a callback that will be triggered when the system is disposed.
  55009. */
  55010. set: function (callback) {
  55011. if (this._onDisposeObserver) {
  55012. this.onDisposeObservable.remove(this._onDisposeObserver);
  55013. }
  55014. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55015. },
  55016. enumerable: true,
  55017. configurable: true
  55018. });
  55019. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55020. /**
  55021. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55022. */
  55023. get: function () {
  55024. return this._isAnimationSheetEnabled;
  55025. },
  55026. enumerable: true,
  55027. configurable: true
  55028. });
  55029. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55030. //end of Sub-emitter
  55031. /**
  55032. * Gets the current list of active particles
  55033. */
  55034. get: function () {
  55035. return this._particles;
  55036. },
  55037. enumerable: true,
  55038. configurable: true
  55039. });
  55040. /**
  55041. * Returns the string "ParticleSystem"
  55042. * @returns a string containing the class name
  55043. */
  55044. ParticleSystem.prototype.getClassName = function () {
  55045. return "ParticleSystem";
  55046. };
  55047. ParticleSystem.prototype._createIndexBuffer = function () {
  55048. var indices = [];
  55049. var index = 0;
  55050. for (var count = 0; count < this._capacity; count++) {
  55051. indices.push(index);
  55052. indices.push(index + 1);
  55053. indices.push(index + 2);
  55054. indices.push(index);
  55055. indices.push(index + 2);
  55056. indices.push(index + 3);
  55057. index += 4;
  55058. }
  55059. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55060. };
  55061. /**
  55062. * Gets the maximum number of particles active at the same time.
  55063. * @returns The max number of active particles.
  55064. */
  55065. ParticleSystem.prototype.getCapacity = function () {
  55066. return this._capacity;
  55067. };
  55068. /**
  55069. * Gets Wether there are still active particles in the system.
  55070. * @returns True if it is alive, otherwise false.
  55071. */
  55072. ParticleSystem.prototype.isAlive = function () {
  55073. return this._alive;
  55074. };
  55075. /**
  55076. * Gets Wether the system has been started.
  55077. * @returns True if it has been started, otherwise false.
  55078. */
  55079. ParticleSystem.prototype.isStarted = function () {
  55080. return this._started;
  55081. };
  55082. /**
  55083. * Starts the particle system and begins to emit.
  55084. */
  55085. ParticleSystem.prototype.start = function () {
  55086. this._started = true;
  55087. this._stopped = false;
  55088. this._actualFrame = 0;
  55089. if (this.subEmitters && this.subEmitters.length != 0) {
  55090. this.activeSubSystems = new Array();
  55091. }
  55092. };
  55093. /**
  55094. * Stops the particle system.
  55095. * @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.
  55096. */
  55097. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55098. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55099. this._stopped = true;
  55100. if (stopSubEmitters) {
  55101. this._stopSubEmitters();
  55102. }
  55103. };
  55104. // animation sheet
  55105. /**
  55106. * Remove all active particles
  55107. */
  55108. ParticleSystem.prototype.reset = function () {
  55109. this._stockParticles = [];
  55110. this._particles = [];
  55111. };
  55112. /**
  55113. * @ignore (for internal use only)
  55114. */
  55115. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55116. var offset = index * this._vertexBufferSize;
  55117. this._vertexData[offset] = particle.position.x;
  55118. this._vertexData[offset + 1] = particle.position.y;
  55119. this._vertexData[offset + 2] = particle.position.z;
  55120. this._vertexData[offset + 3] = particle.color.r;
  55121. this._vertexData[offset + 4] = particle.color.g;
  55122. this._vertexData[offset + 5] = particle.color.b;
  55123. this._vertexData[offset + 6] = particle.color.a;
  55124. this._vertexData[offset + 7] = particle.angle;
  55125. this._vertexData[offset + 8] = particle.size;
  55126. this._vertexData[offset + 9] = offsetX;
  55127. this._vertexData[offset + 10] = offsetY;
  55128. };
  55129. /**
  55130. * @ignore (for internal use only)
  55131. */
  55132. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55133. if (offsetX === 0)
  55134. offsetX = this._epsilon;
  55135. else if (offsetX === 1)
  55136. offsetX = 1 - this._epsilon;
  55137. if (offsetY === 0)
  55138. offsetY = this._epsilon;
  55139. else if (offsetY === 1)
  55140. offsetY = 1 - this._epsilon;
  55141. var offset = index * this._vertexBufferSize;
  55142. this._vertexData[offset] = particle.position.x;
  55143. this._vertexData[offset + 1] = particle.position.y;
  55144. this._vertexData[offset + 2] = particle.position.z;
  55145. this._vertexData[offset + 3] = particle.color.r;
  55146. this._vertexData[offset + 4] = particle.color.g;
  55147. this._vertexData[offset + 5] = particle.color.b;
  55148. this._vertexData[offset + 6] = particle.color.a;
  55149. this._vertexData[offset + 7] = particle.angle;
  55150. this._vertexData[offset + 8] = particle.size;
  55151. this._vertexData[offset + 9] = offsetX;
  55152. this._vertexData[offset + 10] = offsetY;
  55153. this._vertexData[offset + 11] = particle.cellIndex;
  55154. };
  55155. ParticleSystem.prototype._stopSubEmitters = function () {
  55156. if (!this.activeSubSystems) {
  55157. return;
  55158. }
  55159. this.activeSubSystems.forEach(function (subSystem) {
  55160. subSystem.stop(true);
  55161. });
  55162. this.activeSubSystems = new Array();
  55163. };
  55164. ParticleSystem.prototype._removeFromRoot = function () {
  55165. if (!this._rootParticleSystem) {
  55166. return;
  55167. }
  55168. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55169. if (index !== -1) {
  55170. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55171. }
  55172. };
  55173. // end of sub system methods
  55174. ParticleSystem.prototype._update = function (newParticles) {
  55175. // Update current
  55176. this._alive = this._particles.length > 0;
  55177. this.updateFunction(this._particles);
  55178. // Add new ones
  55179. var worldMatrix;
  55180. if (this.emitter.position) {
  55181. var emitterMesh = this.emitter;
  55182. worldMatrix = emitterMesh.getWorldMatrix();
  55183. }
  55184. else {
  55185. var emitterPosition = this.emitter;
  55186. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55187. }
  55188. var particle;
  55189. for (var index = 0; index < newParticles; index++) {
  55190. if (this._particles.length === this._capacity) {
  55191. break;
  55192. }
  55193. particle = this._createParticle();
  55194. this._particles.push(particle);
  55195. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55196. if (this.startPositionFunction) {
  55197. this.startPositionFunction(worldMatrix, particle.position, particle);
  55198. }
  55199. else {
  55200. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55201. }
  55202. if (this.startDirectionFunction) {
  55203. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55204. }
  55205. else {
  55206. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55207. }
  55208. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55209. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55210. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55211. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55212. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55213. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55214. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55215. }
  55216. };
  55217. ParticleSystem.prototype._getEffect = function () {
  55218. if (this._customEffect) {
  55219. return this._customEffect;
  55220. }
  55221. ;
  55222. var defines = [];
  55223. if (this._scene.clipPlane) {
  55224. defines.push("#define CLIPPLANE");
  55225. }
  55226. if (this._isAnimationSheetEnabled) {
  55227. defines.push("#define ANIMATESHEET");
  55228. }
  55229. // Effect
  55230. var join = defines.join("\n");
  55231. if (this._cachedDefines !== join) {
  55232. this._cachedDefines = join;
  55233. var attributesNamesOrOptions;
  55234. var effectCreationOption;
  55235. if (this._isAnimationSheetEnabled) {
  55236. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55237. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55238. }
  55239. else {
  55240. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55241. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55242. }
  55243. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55244. }
  55245. return this._effect;
  55246. };
  55247. /**
  55248. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55249. */
  55250. ParticleSystem.prototype.animate = function () {
  55251. if (!this._started)
  55252. return;
  55253. var effect = this._getEffect();
  55254. // Check
  55255. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55256. return;
  55257. if (this._currentRenderId === this._scene.getRenderId()) {
  55258. return;
  55259. }
  55260. this._currentRenderId = this._scene.getRenderId();
  55261. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55262. // determine the number of particles we need to create
  55263. var newParticles;
  55264. if (this.manualEmitCount > -1) {
  55265. newParticles = this.manualEmitCount;
  55266. this._newPartsExcess = 0;
  55267. this.manualEmitCount = 0;
  55268. }
  55269. else {
  55270. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55271. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55272. }
  55273. if (this._newPartsExcess > 1.0) {
  55274. newParticles += this._newPartsExcess >> 0;
  55275. this._newPartsExcess -= this._newPartsExcess >> 0;
  55276. }
  55277. this._alive = false;
  55278. if (!this._stopped) {
  55279. this._actualFrame += this._scaledUpdateSpeed;
  55280. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55281. this.stop();
  55282. }
  55283. else {
  55284. newParticles = 0;
  55285. }
  55286. this._update(newParticles);
  55287. // Stopped?
  55288. if (this._stopped) {
  55289. if (!this._alive) {
  55290. this._started = false;
  55291. if (this.onAnimationEnd) {
  55292. this.onAnimationEnd();
  55293. }
  55294. if (this.disposeOnStop) {
  55295. this._scene._toBeDisposed.push(this);
  55296. }
  55297. }
  55298. }
  55299. // Animation sheet
  55300. if (this._isAnimationSheetEnabled) {
  55301. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55302. }
  55303. else {
  55304. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55305. }
  55306. // Update VBO
  55307. var offset = 0;
  55308. for (var index = 0; index < this._particles.length; index++) {
  55309. var particle = this._particles[index];
  55310. this._appendParticleVertexes(offset, particle);
  55311. offset += 4;
  55312. }
  55313. if (this._vertexBuffer) {
  55314. this._vertexBuffer.update(this._vertexData);
  55315. }
  55316. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55317. this.stop();
  55318. }
  55319. };
  55320. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55321. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55322. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55323. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55324. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55325. };
  55326. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55327. this._appendParticleVertex(offset++, particle, 0, 0);
  55328. this._appendParticleVertex(offset++, particle, 1, 0);
  55329. this._appendParticleVertex(offset++, particle, 1, 1);
  55330. this._appendParticleVertex(offset++, particle, 0, 1);
  55331. };
  55332. /**
  55333. * Rebuilds the particle system.
  55334. */
  55335. ParticleSystem.prototype.rebuild = function () {
  55336. this._createIndexBuffer();
  55337. if (this._vertexBuffer) {
  55338. this._vertexBuffer._rebuild();
  55339. }
  55340. };
  55341. /**
  55342. * Is this system ready to be used/rendered
  55343. * @return true if the system is ready
  55344. */
  55345. ParticleSystem.prototype.isReady = function () {
  55346. var effect = this._getEffect();
  55347. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55348. return false;
  55349. }
  55350. return true;
  55351. };
  55352. /**
  55353. * Renders the particle system in its current state.
  55354. * @returns the current number of particles
  55355. */
  55356. ParticleSystem.prototype.render = function () {
  55357. var effect = this._getEffect();
  55358. // Check
  55359. if (!this.isReady() || !this._particles.length) {
  55360. return 0;
  55361. }
  55362. var engine = this._scene.getEngine();
  55363. // Render
  55364. engine.enableEffect(effect);
  55365. engine.setState(false);
  55366. var viewMatrix = this._scene.getViewMatrix();
  55367. effect.setTexture("diffuseSampler", this.particleTexture);
  55368. effect.setMatrix("view", viewMatrix);
  55369. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55370. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55371. var baseSize = this.particleTexture.getBaseSize();
  55372. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55373. }
  55374. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55375. if (this._scene.clipPlane) {
  55376. var clipPlane = this._scene.clipPlane;
  55377. var invView = viewMatrix.clone();
  55378. invView.invert();
  55379. effect.setMatrix("invView", invView);
  55380. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55381. }
  55382. // VBOs
  55383. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55384. // Draw order
  55385. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55386. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55387. }
  55388. else {
  55389. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55390. }
  55391. if (this.forceDepthWrite) {
  55392. engine.setDepthWrite(true);
  55393. }
  55394. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55395. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55396. return this._particles.length;
  55397. };
  55398. /**
  55399. * Disposes the particle system and free the associated resources
  55400. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55401. */
  55402. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55403. if (disposeTexture === void 0) { disposeTexture = true; }
  55404. if (this._vertexBuffer) {
  55405. this._vertexBuffer.dispose();
  55406. this._vertexBuffer = null;
  55407. }
  55408. if (this._indexBuffer) {
  55409. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55410. this._indexBuffer = null;
  55411. }
  55412. if (disposeTexture && this.particleTexture) {
  55413. this.particleTexture.dispose();
  55414. this.particleTexture = null;
  55415. }
  55416. this._removeFromRoot();
  55417. // Remove from scene
  55418. var index = this._scene.particleSystems.indexOf(this);
  55419. if (index > -1) {
  55420. this._scene.particleSystems.splice(index, 1);
  55421. }
  55422. // Callback
  55423. this.onDisposeObservable.notifyObservers(this);
  55424. this.onDisposeObservable.clear();
  55425. };
  55426. /**
  55427. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55428. * @param radius The radius of the sphere to emit from
  55429. * @returns the emitter
  55430. */
  55431. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55432. if (radius === void 0) { radius = 1; }
  55433. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55434. this.particleEmitterType = particleEmitter;
  55435. return particleEmitter;
  55436. };
  55437. /**
  55438. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55439. * @param radius The radius of the sphere to emit from
  55440. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55441. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55442. * @returns the emitter
  55443. */
  55444. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55445. if (radius === void 0) { radius = 1; }
  55446. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55447. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55448. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55449. this.particleEmitterType = particleEmitter;
  55450. return particleEmitter;
  55451. };
  55452. /**
  55453. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55454. * @param radius The radius of the cone to emit from
  55455. * @param angle The base angle of the cone
  55456. * @returns the emitter
  55457. */
  55458. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55459. if (radius === void 0) { radius = 1; }
  55460. if (angle === void 0) { angle = Math.PI / 4; }
  55461. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55462. this.particleEmitterType = particleEmitter;
  55463. return particleEmitter;
  55464. };
  55465. // 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.
  55466. /**
  55467. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55468. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55469. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55470. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55471. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55472. * @returns the emitter
  55473. */
  55474. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55475. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55476. this.particleEmitterType = particleEmitter;
  55477. this.direction1 = direction1;
  55478. this.direction2 = direction2;
  55479. this.minEmitBox = minEmitBox;
  55480. this.maxEmitBox = maxEmitBox;
  55481. return particleEmitter;
  55482. };
  55483. // Clone
  55484. /**
  55485. * Clones the particle system.
  55486. * @param name The name of the cloned object
  55487. * @param newEmitter The new emitter to use
  55488. * @returns the cloned particle system
  55489. */
  55490. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55491. var custom = null;
  55492. var program = null;
  55493. if (this.customShader != null) {
  55494. program = this.customShader;
  55495. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55496. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55497. }
  55498. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55499. result.customShader = program;
  55500. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55501. if (newEmitter === undefined) {
  55502. newEmitter = this.emitter;
  55503. }
  55504. result.emitter = newEmitter;
  55505. if (this.particleTexture) {
  55506. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55507. }
  55508. if (!this.preventAutoStart) {
  55509. result.start();
  55510. }
  55511. return result;
  55512. };
  55513. /**
  55514. * Serializes the particle system to a JSON object.
  55515. * @returns the JSON object
  55516. */
  55517. ParticleSystem.prototype.serialize = function () {
  55518. var serializationObject = {};
  55519. serializationObject.name = this.name;
  55520. serializationObject.id = this.id;
  55521. // Emitter
  55522. if (this.emitter.position) {
  55523. var emitterMesh = this.emitter;
  55524. serializationObject.emitterId = emitterMesh.id;
  55525. }
  55526. else {
  55527. var emitterPosition = this.emitter;
  55528. serializationObject.emitter = emitterPosition.asArray();
  55529. }
  55530. serializationObject.capacity = this.getCapacity();
  55531. if (this.particleTexture) {
  55532. serializationObject.textureName = this.particleTexture.name;
  55533. }
  55534. // Animations
  55535. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55536. // Particle system
  55537. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55538. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55539. serializationObject.minSize = this.minSize;
  55540. serializationObject.maxSize = this.maxSize;
  55541. serializationObject.minEmitPower = this.minEmitPower;
  55542. serializationObject.maxEmitPower = this.maxEmitPower;
  55543. serializationObject.minLifeTime = this.minLifeTime;
  55544. serializationObject.maxLifeTime = this.maxLifeTime;
  55545. serializationObject.emitRate = this.emitRate;
  55546. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55547. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55548. serializationObject.gravity = this.gravity.asArray();
  55549. serializationObject.direction1 = this.direction1.asArray();
  55550. serializationObject.direction2 = this.direction2.asArray();
  55551. serializationObject.color1 = this.color1.asArray();
  55552. serializationObject.color2 = this.color2.asArray();
  55553. serializationObject.colorDead = this.colorDead.asArray();
  55554. serializationObject.updateSpeed = this.updateSpeed;
  55555. serializationObject.targetStopDuration = this.targetStopDuration;
  55556. serializationObject.textureMask = this.textureMask.asArray();
  55557. serializationObject.blendMode = this.blendMode;
  55558. serializationObject.customShader = this.customShader;
  55559. serializationObject.preventAutoStart = this.preventAutoStart;
  55560. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55561. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55562. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55563. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55564. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55565. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55566. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55567. // Emitter
  55568. if (this.particleEmitterType) {
  55569. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55570. }
  55571. return serializationObject;
  55572. };
  55573. /**
  55574. * Parses a JSON object to create a particle system.
  55575. * @param parsedParticleSystem The JSON object to parse
  55576. * @param scene The scene to create the particle system in
  55577. * @param rootUrl The root url to use to load external dependencies like texture
  55578. * @returns the Parsed particle system
  55579. */
  55580. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55581. var name = parsedParticleSystem.name;
  55582. var custom = null;
  55583. var program = null;
  55584. if (parsedParticleSystem.customShader) {
  55585. program = parsedParticleSystem.customShader;
  55586. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55587. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55588. }
  55589. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55590. particleSystem.customShader = program;
  55591. if (parsedParticleSystem.id) {
  55592. particleSystem.id = parsedParticleSystem.id;
  55593. }
  55594. // Auto start
  55595. if (parsedParticleSystem.preventAutoStart) {
  55596. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55597. }
  55598. // Texture
  55599. if (parsedParticleSystem.textureName) {
  55600. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55601. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55602. }
  55603. // Emitter
  55604. if (parsedParticleSystem.emitterId) {
  55605. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55606. }
  55607. else {
  55608. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55609. }
  55610. // Animations
  55611. if (parsedParticleSystem.animations) {
  55612. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55613. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55614. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55615. }
  55616. }
  55617. if (parsedParticleSystem.autoAnimate) {
  55618. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55619. }
  55620. // Particle system
  55621. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55622. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55623. particleSystem.minSize = parsedParticleSystem.minSize;
  55624. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55625. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55626. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55627. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55628. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55629. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55630. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55631. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55632. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55633. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55634. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55635. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55636. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55637. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55638. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55639. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55640. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55641. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55642. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55643. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55644. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55645. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55646. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55647. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55648. if (!particleSystem.preventAutoStart) {
  55649. particleSystem.start();
  55650. }
  55651. return particleSystem;
  55652. };
  55653. /**
  55654. * Source color is added to the destination color without alpha affecting the result.
  55655. */
  55656. ParticleSystem.BLENDMODE_ONEONE = 0;
  55657. /**
  55658. * Blend current color and particle color using particle’s alpha.
  55659. */
  55660. ParticleSystem.BLENDMODE_STANDARD = 1;
  55661. return ParticleSystem;
  55662. }());
  55663. BABYLON.ParticleSystem = ParticleSystem;
  55664. })(BABYLON || (BABYLON = {}));
  55665. //# sourceMappingURL=babylon.particleSystem.js.map
  55666. "use strict";
  55667. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55668. "use strict";
  55669. var BABYLON;
  55670. (function (BABYLON) {
  55671. /**
  55672. * Particle emitter emitting particles from the inside of a box.
  55673. * It emits the particles randomly between 2 given directions.
  55674. */
  55675. var BoxParticleEmitter = /** @class */ (function () {
  55676. /**
  55677. * Creates a new instance BoxParticleEmitter
  55678. */
  55679. function BoxParticleEmitter() {
  55680. /**
  55681. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55682. */
  55683. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55684. /**
  55685. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55686. */
  55687. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55688. /**
  55689. * 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.
  55690. */
  55691. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55692. /**
  55693. * 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.
  55694. */
  55695. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55696. }
  55697. /**
  55698. * Called by the particle System when the direction is computed for the created particle.
  55699. * @param emitPower is the power of the particle (speed)
  55700. * @param worldMatrix is the world matrix of the particle system
  55701. * @param directionToUpdate is the direction vector to update with the result
  55702. * @param particle is the particle we are computed the direction for
  55703. */
  55704. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55705. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55706. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55707. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55708. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55709. };
  55710. /**
  55711. * Called by the particle System when the position is computed for the created particle.
  55712. * @param worldMatrix is the world matrix of the particle system
  55713. * @param positionToUpdate is the position vector to update with the result
  55714. * @param particle is the particle we are computed the position for
  55715. */
  55716. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55717. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55718. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55719. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55720. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55721. };
  55722. /**
  55723. * Clones the current emitter and returns a copy of it
  55724. * @returns the new emitter
  55725. */
  55726. BoxParticleEmitter.prototype.clone = function () {
  55727. var newOne = new BoxParticleEmitter();
  55728. BABYLON.Tools.DeepCopy(this, newOne);
  55729. return newOne;
  55730. };
  55731. /**
  55732. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55733. * @param effect defines the update shader
  55734. */
  55735. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55736. effect.setVector3("direction1", this.direction1);
  55737. effect.setVector3("direction2", this.direction2);
  55738. effect.setVector3("minEmitBox", this.minEmitBox);
  55739. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55740. };
  55741. /**
  55742. * Returns a string to use to update the GPU particles update shader
  55743. * @returns a string containng the defines string
  55744. */
  55745. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55746. return "#define BOXEMITTER";
  55747. };
  55748. /**
  55749. * Returns the string "BoxEmitter"
  55750. * @returns a string containing the class name
  55751. */
  55752. BoxParticleEmitter.prototype.getClassName = function () {
  55753. return "BoxEmitter";
  55754. };
  55755. /**
  55756. * Serializes the particle system to a JSON object.
  55757. * @returns the JSON object
  55758. */
  55759. BoxParticleEmitter.prototype.serialize = function () {
  55760. var serializationObject = {};
  55761. serializationObject.type = this.getClassName();
  55762. serializationObject.direction1 = this.direction1.asArray();
  55763. ;
  55764. serializationObject.direction2 = this.direction2.asArray();
  55765. ;
  55766. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55767. ;
  55768. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55769. ;
  55770. return serializationObject;
  55771. };
  55772. /**
  55773. * Parse properties from a JSON object
  55774. * @param serializationObject defines the JSON object
  55775. */
  55776. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55777. this.direction1.copyFrom(serializationObject.direction1);
  55778. this.direction2.copyFrom(serializationObject.direction2);
  55779. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55780. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55781. };
  55782. return BoxParticleEmitter;
  55783. }());
  55784. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55785. })(BABYLON || (BABYLON = {}));
  55786. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55787. "use strict";
  55788. var BABYLON;
  55789. (function (BABYLON) {
  55790. /**
  55791. * Particle emitter emitting particles from the inside of a cone.
  55792. * It emits the particles alongside the cone volume from the base to the particle.
  55793. * The emission direction might be randomized.
  55794. */
  55795. var ConeParticleEmitter = /** @class */ (function () {
  55796. /**
  55797. * Creates a new instance ConeParticleEmitter
  55798. * @param radius the radius of the emission cone (1 by default)
  55799. * @param angles the cone base angle (PI by default)
  55800. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55801. */
  55802. function ConeParticleEmitter(radius,
  55803. /**
  55804. * The radius of the emission cone.
  55805. */
  55806. angle,
  55807. /**
  55808. * The cone base angle.
  55809. */
  55810. directionRandomizer) {
  55811. if (radius === void 0) { radius = 1; }
  55812. if (angle === void 0) { angle = Math.PI; }
  55813. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55814. this.angle = angle;
  55815. this.directionRandomizer = directionRandomizer;
  55816. this.radius = radius;
  55817. }
  55818. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55819. /**
  55820. * Gets the radius of the emission cone.
  55821. */
  55822. get: function () {
  55823. return this._radius;
  55824. },
  55825. /**
  55826. * Sets the radius of the emission cone.
  55827. */
  55828. set: function (value) {
  55829. this._radius = value;
  55830. if (this.angle !== 0) {
  55831. this._height = value / Math.tan(this.angle / 2);
  55832. }
  55833. else {
  55834. this._height = 1;
  55835. }
  55836. },
  55837. enumerable: true,
  55838. configurable: true
  55839. });
  55840. /**
  55841. * Called by the particle System when the direction is computed for the created particle.
  55842. * @param emitPower is the power of the particle (speed)
  55843. * @param worldMatrix is the world matrix of the particle system
  55844. * @param directionToUpdate is the direction vector to update with the result
  55845. * @param particle is the particle we are computed the direction for
  55846. */
  55847. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55848. if (this.angle === 0) {
  55849. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55850. }
  55851. else {
  55852. // measure the direction Vector from the emitter to the particle.
  55853. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55854. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55855. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55856. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55857. direction.x += randX;
  55858. direction.y += randY;
  55859. direction.z += randZ;
  55860. direction.normalize();
  55861. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55862. }
  55863. };
  55864. /**
  55865. * Called by the particle System when the position is computed for the created particle.
  55866. * @param worldMatrix is the world matrix of the particle system
  55867. * @param positionToUpdate is the position vector to update with the result
  55868. * @param particle is the particle we are computed the position for
  55869. */
  55870. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55871. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  55872. var h = BABYLON.Scalar.RandomRange(0, 1);
  55873. // Better distribution in a cone at normal angles.
  55874. h = 1 - h * h;
  55875. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  55876. radius = radius * h;
  55877. var randX = radius * Math.sin(s);
  55878. var randZ = radius * Math.cos(s);
  55879. var randY = h * this._height;
  55880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55881. };
  55882. /**
  55883. * Clones the current emitter and returns a copy of it
  55884. * @returns the new emitter
  55885. */
  55886. ConeParticleEmitter.prototype.clone = function () {
  55887. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55888. BABYLON.Tools.DeepCopy(this, newOne);
  55889. return newOne;
  55890. };
  55891. /**
  55892. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55893. * @param effect defines the update shader
  55894. */
  55895. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55896. effect.setFloat("radius", this.radius);
  55897. effect.setFloat("angle", this.angle);
  55898. effect.setFloat("height", this._height);
  55899. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55900. };
  55901. /**
  55902. * Returns a string to use to update the GPU particles update shader
  55903. * @returns a string containng the defines string
  55904. */
  55905. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55906. return "#define CONEEMITTER";
  55907. };
  55908. /**
  55909. * Returns the string "BoxEmitter"
  55910. * @returns a string containing the class name
  55911. */
  55912. ConeParticleEmitter.prototype.getClassName = function () {
  55913. return "ConeEmitter";
  55914. };
  55915. /**
  55916. * Serializes the particle system to a JSON object.
  55917. * @returns the JSON object
  55918. */
  55919. ConeParticleEmitter.prototype.serialize = function () {
  55920. var serializationObject = {};
  55921. serializationObject.type = this.getClassName();
  55922. serializationObject.radius = this.radius;
  55923. serializationObject.angle = this.angle;
  55924. serializationObject.directionRandomizer = this.directionRandomizer;
  55925. return serializationObject;
  55926. };
  55927. /**
  55928. * Parse properties from a JSON object
  55929. * @param serializationObject defines the JSON object
  55930. */
  55931. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55932. this.radius = serializationObject.radius;
  55933. this.angle = serializationObject.angle;
  55934. this.directionRandomizer = serializationObject.directionRandomizer;
  55935. };
  55936. return ConeParticleEmitter;
  55937. }());
  55938. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55939. })(BABYLON || (BABYLON = {}));
  55940. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55941. "use strict";
  55942. var BABYLON;
  55943. (function (BABYLON) {
  55944. /**
  55945. * Particle emitter emitting particles from the inside of a sphere.
  55946. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55947. */
  55948. var SphereParticleEmitter = /** @class */ (function () {
  55949. /**
  55950. * Creates a new instance SphereParticleEmitter
  55951. * @param radius the radius of the emission sphere (1 by default)
  55952. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55953. */
  55954. function SphereParticleEmitter(
  55955. /**
  55956. * The radius of the emission sphere.
  55957. */
  55958. radius,
  55959. /**
  55960. * How much to randomize the particle direction [0-1].
  55961. */
  55962. directionRandomizer) {
  55963. if (radius === void 0) { radius = 1; }
  55964. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55965. this.radius = radius;
  55966. this.directionRandomizer = directionRandomizer;
  55967. }
  55968. /**
  55969. * Called by the particle System when the direction is computed for the created particle.
  55970. * @param emitPower is the power of the particle (speed)
  55971. * @param worldMatrix is the world matrix of the particle system
  55972. * @param directionToUpdate is the direction vector to update with the result
  55973. * @param particle is the particle we are computed the direction for
  55974. */
  55975. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55976. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55977. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55978. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55979. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55980. direction.x += randX;
  55981. direction.y += randY;
  55982. direction.z += randZ;
  55983. direction.normalize();
  55984. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55985. };
  55986. /**
  55987. * Called by the particle System when the position is computed for the created particle.
  55988. * @param worldMatrix is the world matrix of the particle system
  55989. * @param positionToUpdate is the position vector to update with the result
  55990. * @param particle is the particle we are computed the position for
  55991. */
  55992. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55993. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55994. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55995. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55996. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55997. var randY = randRadius * Math.cos(theta);
  55998. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55999. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56000. };
  56001. /**
  56002. * Clones the current emitter and returns a copy of it
  56003. * @returns the new emitter
  56004. */
  56005. SphereParticleEmitter.prototype.clone = function () {
  56006. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56007. BABYLON.Tools.DeepCopy(this, newOne);
  56008. return newOne;
  56009. };
  56010. /**
  56011. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56012. * @param effect defines the update shader
  56013. */
  56014. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56015. effect.setFloat("radius", this.radius);
  56016. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56017. };
  56018. /**
  56019. * Returns a string to use to update the GPU particles update shader
  56020. * @returns a string containng the defines string
  56021. */
  56022. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56023. return "#define SPHEREEMITTER";
  56024. };
  56025. /**
  56026. * Returns the string "SphereParticleEmitter"
  56027. * @returns a string containing the class name
  56028. */
  56029. SphereParticleEmitter.prototype.getClassName = function () {
  56030. return "SphereParticleEmitter";
  56031. };
  56032. /**
  56033. * Serializes the particle system to a JSON object.
  56034. * @returns the JSON object
  56035. */
  56036. SphereParticleEmitter.prototype.serialize = function () {
  56037. var serializationObject = {};
  56038. serializationObject.type = this.getClassName();
  56039. serializationObject.radius = this.radius;
  56040. serializationObject.directionRandomizer = this.directionRandomizer;
  56041. return serializationObject;
  56042. };
  56043. /**
  56044. * Parse properties from a JSON object
  56045. * @param serializationObject defines the JSON object
  56046. */
  56047. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56048. this.radius = serializationObject.radius;
  56049. this.directionRandomizer = serializationObject.directionRandomizer;
  56050. };
  56051. return SphereParticleEmitter;
  56052. }());
  56053. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56054. /**
  56055. * Particle emitter emitting particles from the inside of a sphere.
  56056. * It emits the particles randomly between two vectors.
  56057. */
  56058. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56059. __extends(SphereDirectedParticleEmitter, _super);
  56060. /**
  56061. * Creates a new instance SphereDirectedParticleEmitter
  56062. * @param radius the radius of the emission sphere (1 by default)
  56063. * @param direction1 the min limit of the emission direction (up vector by default)
  56064. * @param direction2 the max limit of the emission direction (up vector by default)
  56065. */
  56066. function SphereDirectedParticleEmitter(radius,
  56067. /**
  56068. * The min limit of the emission direction.
  56069. */
  56070. direction1,
  56071. /**
  56072. * The max limit of the emission direction.
  56073. */
  56074. direction2) {
  56075. if (radius === void 0) { radius = 1; }
  56076. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56077. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56078. var _this = _super.call(this, radius) || this;
  56079. _this.direction1 = direction1;
  56080. _this.direction2 = direction2;
  56081. return _this;
  56082. }
  56083. /**
  56084. * Called by the particle System when the direction is computed for the created particle.
  56085. * @param emitPower is the power of the particle (speed)
  56086. * @param worldMatrix is the world matrix of the particle system
  56087. * @param directionToUpdate is the direction vector to update with the result
  56088. * @param particle is the particle we are computed the direction for
  56089. */
  56090. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56091. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56092. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56093. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56094. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56095. };
  56096. /**
  56097. * Clones the current emitter and returns a copy of it
  56098. * @returns the new emitter
  56099. */
  56100. SphereDirectedParticleEmitter.prototype.clone = function () {
  56101. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56102. BABYLON.Tools.DeepCopy(this, newOne);
  56103. return newOne;
  56104. };
  56105. /**
  56106. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56107. * @param effect defines the update shader
  56108. */
  56109. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56110. effect.setFloat("radius", this.radius);
  56111. effect.setVector3("direction1", this.direction1);
  56112. effect.setVector3("direction2", this.direction2);
  56113. };
  56114. /**
  56115. * Returns a string to use to update the GPU particles update shader
  56116. * @returns a string containng the defines string
  56117. */
  56118. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56119. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56120. };
  56121. /**
  56122. * Returns the string "SphereDirectedParticleEmitter"
  56123. * @returns a string containing the class name
  56124. */
  56125. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56126. return "SphereDirectedParticleEmitter";
  56127. };
  56128. /**
  56129. * Serializes the particle system to a JSON object.
  56130. * @returns the JSON object
  56131. */
  56132. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56133. var serializationObject = _super.prototype.serialize.call(this);
  56134. ;
  56135. serializationObject.direction1 = this.direction1.asArray();
  56136. ;
  56137. serializationObject.direction2 = this.direction2.asArray();
  56138. ;
  56139. return serializationObject;
  56140. };
  56141. /**
  56142. * Parse properties from a JSON object
  56143. * @param serializationObject defines the JSON object
  56144. */
  56145. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56146. _super.prototype.parse.call(this, serializationObject);
  56147. this.direction1.copyFrom(serializationObject.direction1);
  56148. this.direction2.copyFrom(serializationObject.direction2);
  56149. };
  56150. return SphereDirectedParticleEmitter;
  56151. }(SphereParticleEmitter));
  56152. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56153. })(BABYLON || (BABYLON = {}));
  56154. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56155. "use strict";
  56156. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56157. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56158. s = arguments[i];
  56159. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56160. t[p] = s[p];
  56161. }
  56162. return t;
  56163. };
  56164. var BABYLON;
  56165. (function (BABYLON) {
  56166. /**
  56167. * This represents a GPU particle system in Babylon
  56168. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56169. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56170. */
  56171. var GPUParticleSystem = /** @class */ (function () {
  56172. /**
  56173. * Instantiates a GPU particle system.
  56174. * 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.
  56175. * @param name The name of the particle system
  56176. * @param capacity The max number of particles alive at the same time
  56177. * @param scene The scene the particle system belongs to
  56178. */
  56179. function GPUParticleSystem(name, options, scene) {
  56180. /**
  56181. * The emitter represents the Mesh or position we are attaching the particle system to.
  56182. */
  56183. this.emitter = null;
  56184. /**
  56185. * The rendering group used by the Particle system to chose when to render.
  56186. */
  56187. this.renderingGroupId = 0;
  56188. /**
  56189. * The layer mask we are rendering the particles through.
  56190. */
  56191. this.layerMask = 0x0FFFFFFF;
  56192. this._targetIndex = 0;
  56193. this._currentRenderId = -1;
  56194. this._started = false;
  56195. this._stopped = false;
  56196. this._timeDelta = 0;
  56197. this._attributesStrideSize = 14;
  56198. this._actualFrame = 0;
  56199. /**
  56200. * List of animations used by the particle system.
  56201. */
  56202. this.animations = [];
  56203. /**
  56204. * An event triggered when the system is disposed.
  56205. */
  56206. this.onDisposeObservable = new BABYLON.Observable();
  56207. /**
  56208. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56209. */
  56210. this.updateSpeed = 0.01;
  56211. /**
  56212. * The amount of time the particle system is running (depends of the overall update speed).
  56213. */
  56214. this.targetStopDuration = 0;
  56215. /**
  56216. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56217. */
  56218. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56219. /**
  56220. * Minimum life time of emitting particles.
  56221. */
  56222. this.minLifeTime = 1;
  56223. /**
  56224. * Maximum life time of emitting particles.
  56225. */
  56226. this.maxLifeTime = 1;
  56227. /**
  56228. * Minimum Size of emitting particles.
  56229. */
  56230. this.minSize = 1;
  56231. /**
  56232. * Maximum Size of emitting particles.
  56233. */
  56234. this.maxSize = 1;
  56235. /**
  56236. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56237. */
  56238. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56239. /**
  56240. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56241. */
  56242. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56243. /**
  56244. * Color the particle will have at the end of its lifetime.
  56245. */
  56246. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56247. /**
  56248. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56249. */
  56250. this.emitRate = 100;
  56251. /**
  56252. * You can use gravity if you want to give an orientation to your particles.
  56253. */
  56254. this.gravity = BABYLON.Vector3.Zero();
  56255. /**
  56256. * Minimum power of emitting particles.
  56257. */
  56258. this.minEmitPower = 1;
  56259. /**
  56260. * Maximum power of emitting particles.
  56261. */
  56262. this.maxEmitPower = 1;
  56263. /**
  56264. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56265. * to override the particles.
  56266. */
  56267. this.forceDepthWrite = false;
  56268. this.id = name;
  56269. this.name = name;
  56270. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56271. this._engine = this._scene.getEngine();
  56272. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56273. this._capacity = fullOptions.capacity;
  56274. this._activeCount = fullOptions.capacity;
  56275. this._currentActiveCount = 0;
  56276. this._scene.particleSystems.push(this);
  56277. this._updateEffectOptions = {
  56278. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56279. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56280. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56281. uniformBuffersNames: [],
  56282. samplers: ["randomSampler"],
  56283. defines: "",
  56284. fallbacks: null,
  56285. onCompiled: null,
  56286. onError: null,
  56287. indexParameters: null,
  56288. maxSimultaneousLights: 0,
  56289. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56290. };
  56291. // Random data
  56292. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56293. var d = [];
  56294. for (var i = 0; i < maxTextureSize; ++i) {
  56295. d.push(Math.random());
  56296. d.push(Math.random());
  56297. d.push(Math.random());
  56298. d.push(Math.random());
  56299. }
  56300. 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);
  56301. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56302. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56303. this._randomTextureSize = maxTextureSize;
  56304. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56305. }
  56306. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56307. /**
  56308. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56309. */
  56310. get: function () {
  56311. if (!BABYLON.Engine.LastCreatedEngine) {
  56312. return false;
  56313. }
  56314. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56315. },
  56316. enumerable: true,
  56317. configurable: true
  56318. });
  56319. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56320. /**
  56321. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56322. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56323. */
  56324. get: function () {
  56325. if (this.particleEmitterType.direction1) {
  56326. return this.particleEmitterType.direction1;
  56327. }
  56328. return BABYLON.Vector3.Zero();
  56329. },
  56330. set: function (value) {
  56331. if (this.particleEmitterType.direction1) {
  56332. this.particleEmitterType.direction1 = value;
  56333. }
  56334. },
  56335. enumerable: true,
  56336. configurable: true
  56337. });
  56338. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56339. /**
  56340. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56341. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56342. */
  56343. get: function () {
  56344. if (this.particleEmitterType.direction2) {
  56345. return this.particleEmitterType.direction2;
  56346. }
  56347. return BABYLON.Vector3.Zero();
  56348. },
  56349. set: function (value) {
  56350. if (this.particleEmitterType.direction2) {
  56351. this.particleEmitterType.direction2 = value;
  56352. }
  56353. },
  56354. enumerable: true,
  56355. configurable: true
  56356. });
  56357. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56358. /**
  56359. * 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.
  56360. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56361. */
  56362. get: function () {
  56363. if (this.particleEmitterType.minEmitBox) {
  56364. return this.particleEmitterType.minEmitBox;
  56365. }
  56366. return BABYLON.Vector3.Zero();
  56367. },
  56368. set: function (value) {
  56369. if (this.particleEmitterType.minEmitBox) {
  56370. this.particleEmitterType.minEmitBox = value;
  56371. }
  56372. },
  56373. enumerable: true,
  56374. configurable: true
  56375. });
  56376. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56377. /**
  56378. * 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.
  56379. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56380. */
  56381. get: function () {
  56382. if (this.particleEmitterType.maxEmitBox) {
  56383. return this.particleEmitterType.maxEmitBox;
  56384. }
  56385. return BABYLON.Vector3.Zero();
  56386. },
  56387. set: function (value) {
  56388. if (this.particleEmitterType.maxEmitBox) {
  56389. this.particleEmitterType.maxEmitBox = value;
  56390. }
  56391. },
  56392. enumerable: true,
  56393. configurable: true
  56394. });
  56395. /**
  56396. * Gets the maximum number of particles active at the same time.
  56397. * @returns The max number of active particles.
  56398. */
  56399. GPUParticleSystem.prototype.getCapacity = function () {
  56400. return this._capacity;
  56401. };
  56402. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56403. /**
  56404. * Gets or set the number of active particles
  56405. */
  56406. get: function () {
  56407. return this._activeCount;
  56408. },
  56409. set: function (value) {
  56410. this._activeCount = Math.min(value, this._capacity);
  56411. },
  56412. enumerable: true,
  56413. configurable: true
  56414. });
  56415. /**
  56416. * Is this system ready to be used/rendered
  56417. * @return true if the system is ready
  56418. */
  56419. GPUParticleSystem.prototype.isReady = function () {
  56420. if (!this._updateEffect) {
  56421. this._recreateUpdateEffect();
  56422. this._recreateRenderEffect();
  56423. return false;
  56424. }
  56425. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56426. return false;
  56427. }
  56428. return true;
  56429. };
  56430. /**
  56431. * Gets Wether the system has been started.
  56432. * @returns True if it has been started, otherwise false.
  56433. */
  56434. GPUParticleSystem.prototype.isStarted = function () {
  56435. return this._started;
  56436. };
  56437. /**
  56438. * Starts the particle system and begins to emit.
  56439. */
  56440. GPUParticleSystem.prototype.start = function () {
  56441. this._started = true;
  56442. this._stopped = false;
  56443. };
  56444. /**
  56445. * Stops the particle system.
  56446. */
  56447. GPUParticleSystem.prototype.stop = function () {
  56448. this._stopped = true;
  56449. };
  56450. /**
  56451. * Remove all active particles
  56452. */
  56453. GPUParticleSystem.prototype.reset = function () {
  56454. this._releaseBuffers();
  56455. this._releaseVAOs();
  56456. this._currentActiveCount = 0;
  56457. this._targetIndex = 0;
  56458. };
  56459. /**
  56460. * Returns the string "GPUParticleSystem"
  56461. * @returns a string containing the class name
  56462. */
  56463. GPUParticleSystem.prototype.getClassName = function () {
  56464. return "GPUParticleSystem";
  56465. };
  56466. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56467. var updateVertexBuffers = {};
  56468. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56469. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56470. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56471. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56472. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56473. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56474. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56475. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56476. this._engine.bindArrayBuffer(null);
  56477. return vao;
  56478. };
  56479. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56480. var renderVertexBuffers = {};
  56481. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56482. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56483. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56484. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56485. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56486. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56487. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56488. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56489. this._engine.bindArrayBuffer(null);
  56490. return vao;
  56491. };
  56492. GPUParticleSystem.prototype._initialize = function (force) {
  56493. if (force === void 0) { force = false; }
  56494. if (this._buffer0 && !force) {
  56495. return;
  56496. }
  56497. var engine = this._scene.getEngine();
  56498. var data = new Array();
  56499. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56500. // position
  56501. data.push(0.0);
  56502. data.push(0.0);
  56503. data.push(0.0);
  56504. // Age and life
  56505. data.push(0.0); // create the particle as a dead one to create a new one at start
  56506. data.push(0.0);
  56507. // Seed
  56508. data.push(Math.random());
  56509. // Size
  56510. data.push(0.0);
  56511. // color
  56512. data.push(0.0);
  56513. data.push(0.0);
  56514. data.push(0.0);
  56515. data.push(0.0);
  56516. // direction
  56517. data.push(0.0);
  56518. data.push(0.0);
  56519. data.push(0.0);
  56520. }
  56521. // Sprite data
  56522. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56523. -0.5, 0.5, 0, 1,
  56524. -0.5, -0.5, 0, 0,
  56525. 0.5, -0.5, 1, 0]);
  56526. // Buffers
  56527. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56528. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56529. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56530. // Update VAO
  56531. this._updateVAO = [];
  56532. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56533. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56534. // Render VAO
  56535. this._renderVAO = [];
  56536. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56537. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56538. // Links
  56539. this._sourceBuffer = this._buffer0;
  56540. this._targetBuffer = this._buffer1;
  56541. };
  56542. /** @ignore */
  56543. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56544. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56545. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56546. return;
  56547. }
  56548. this._updateEffectOptions.defines = defines;
  56549. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56550. };
  56551. /** @ignore */
  56552. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56553. var defines = "";
  56554. if (this._scene.clipPlane) {
  56555. defines = "\n#define CLIPPLANE";
  56556. }
  56557. if (this._renderEffect && this._renderEffect.defines === defines) {
  56558. return;
  56559. }
  56560. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56561. };
  56562. /**
  56563. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56564. */
  56565. GPUParticleSystem.prototype.animate = function () {
  56566. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56567. this._actualFrame += this._timeDelta;
  56568. if (!this._stopped) {
  56569. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56570. this.stop();
  56571. }
  56572. }
  56573. };
  56574. /**
  56575. * Renders the particle system in its current state.
  56576. * @returns the current number of particles
  56577. */
  56578. GPUParticleSystem.prototype.render = function () {
  56579. if (!this._started) {
  56580. return 0;
  56581. }
  56582. this._recreateUpdateEffect();
  56583. this._recreateRenderEffect();
  56584. if (!this.isReady()) {
  56585. return 0;
  56586. }
  56587. if (this._currentRenderId === this._scene.getRenderId()) {
  56588. return 0;
  56589. }
  56590. this._currentRenderId = this._scene.getRenderId();
  56591. // Get everything ready to render
  56592. this._initialize();
  56593. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56594. // Enable update effect
  56595. this._engine.enableEffect(this._updateEffect);
  56596. this._engine.setState(false);
  56597. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56598. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56599. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56600. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56601. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56602. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56603. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56604. this._updateEffect.setDirectColor4("color1", this.color1);
  56605. this._updateEffect.setDirectColor4("color2", this.color2);
  56606. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56607. this._updateEffect.setVector3("gravity", this.gravity);
  56608. if (this.particleEmitterType) {
  56609. this.particleEmitterType.applyToShader(this._updateEffect);
  56610. }
  56611. var emitterWM;
  56612. if (this.emitter.position) {
  56613. var emitterMesh = this.emitter;
  56614. emitterWM = emitterMesh.getWorldMatrix();
  56615. }
  56616. else {
  56617. var emitterPosition = this.emitter;
  56618. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56619. }
  56620. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56621. // Bind source VAO
  56622. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56623. // Update
  56624. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56625. this._engine.setRasterizerState(false);
  56626. this._engine.beginTransformFeedback();
  56627. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56628. this._engine.endTransformFeedback();
  56629. this._engine.setRasterizerState(true);
  56630. this._engine.bindTransformFeedbackBuffer(null);
  56631. // Enable render effect
  56632. this._engine.enableEffect(this._renderEffect);
  56633. var viewMatrix = this._scene.getViewMatrix();
  56634. this._renderEffect.setMatrix("view", viewMatrix);
  56635. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56636. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56637. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56638. if (this._scene.clipPlane) {
  56639. var clipPlane = this._scene.clipPlane;
  56640. var invView = viewMatrix.clone();
  56641. invView.invert();
  56642. this._renderEffect.setMatrix("invView", invView);
  56643. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56644. }
  56645. // Draw order
  56646. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56647. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56648. }
  56649. else {
  56650. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56651. }
  56652. if (this.forceDepthWrite) {
  56653. this._engine.setDepthWrite(true);
  56654. }
  56655. // Bind source VAO
  56656. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56657. // Render
  56658. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56659. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56660. // Switch VAOs
  56661. this._targetIndex++;
  56662. if (this._targetIndex === 2) {
  56663. this._targetIndex = 0;
  56664. }
  56665. // Switch buffers
  56666. var tmpBuffer = this._sourceBuffer;
  56667. this._sourceBuffer = this._targetBuffer;
  56668. this._targetBuffer = tmpBuffer;
  56669. return this._currentActiveCount;
  56670. };
  56671. /**
  56672. * Rebuilds the particle system
  56673. */
  56674. GPUParticleSystem.prototype.rebuild = function () {
  56675. this._initialize(true);
  56676. };
  56677. GPUParticleSystem.prototype._releaseBuffers = function () {
  56678. if (this._buffer0) {
  56679. this._buffer0.dispose();
  56680. this._buffer0 = null;
  56681. }
  56682. if (this._buffer1) {
  56683. this._buffer1.dispose();
  56684. this._buffer1 = null;
  56685. }
  56686. if (this._spriteBuffer) {
  56687. this._spriteBuffer.dispose();
  56688. this._spriteBuffer = null;
  56689. }
  56690. };
  56691. GPUParticleSystem.prototype._releaseVAOs = function () {
  56692. if (!this._updateVAO) {
  56693. return;
  56694. }
  56695. for (var index = 0; index < this._updateVAO.length; index++) {
  56696. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56697. }
  56698. this._updateVAO = [];
  56699. for (var index = 0; index < this._renderVAO.length; index++) {
  56700. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56701. }
  56702. this._renderVAO = [];
  56703. };
  56704. /**
  56705. * Disposes the particle system and free the associated resources
  56706. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56707. */
  56708. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56709. if (disposeTexture === void 0) { disposeTexture = true; }
  56710. var index = this._scene.particleSystems.indexOf(this);
  56711. if (index > -1) {
  56712. this._scene.particleSystems.splice(index, 1);
  56713. }
  56714. this._releaseBuffers();
  56715. this._releaseVAOs();
  56716. if (this._randomTexture) {
  56717. this._randomTexture.dispose();
  56718. this._randomTexture = null;
  56719. }
  56720. if (disposeTexture && this.particleTexture) {
  56721. this.particleTexture.dispose();
  56722. this.particleTexture = null;
  56723. }
  56724. // Callback
  56725. this.onDisposeObservable.notifyObservers(this);
  56726. this.onDisposeObservable.clear();
  56727. };
  56728. /**
  56729. * Clones the particle system.
  56730. * @param name The name of the cloned object
  56731. * @param newEmitter The new emitter to use
  56732. * @returns the cloned particle system
  56733. */
  56734. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56735. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56736. BABYLON.Tools.DeepCopy(this, result);
  56737. if (newEmitter === undefined) {
  56738. newEmitter = this.emitter;
  56739. }
  56740. result.emitter = newEmitter;
  56741. if (this.particleTexture) {
  56742. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56743. }
  56744. return result;
  56745. };
  56746. /**
  56747. * Serializes the particle system to a JSON object.
  56748. * @returns the JSON object
  56749. */
  56750. GPUParticleSystem.prototype.serialize = function () {
  56751. var serializationObject = {};
  56752. serializationObject.name = this.name;
  56753. serializationObject.id = this.id;
  56754. // Emitter
  56755. if (this.emitter.position) {
  56756. var emitterMesh = this.emitter;
  56757. serializationObject.emitterId = emitterMesh.id;
  56758. }
  56759. else {
  56760. var emitterPosition = this.emitter;
  56761. serializationObject.emitter = emitterPosition.asArray();
  56762. }
  56763. serializationObject.capacity = this.getCapacity();
  56764. if (this.particleTexture) {
  56765. serializationObject.textureName = this.particleTexture.name;
  56766. }
  56767. // Animations
  56768. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56769. // Particle system
  56770. serializationObject.activeParticleCount = this.activeParticleCount;
  56771. serializationObject.randomTextureSize = this._randomTextureSize;
  56772. serializationObject.minSize = this.minSize;
  56773. serializationObject.maxSize = this.maxSize;
  56774. serializationObject.minEmitPower = this.minEmitPower;
  56775. serializationObject.maxEmitPower = this.maxEmitPower;
  56776. serializationObject.minLifeTime = this.minLifeTime;
  56777. serializationObject.maxLifeTime = this.maxLifeTime;
  56778. serializationObject.emitRate = this.emitRate;
  56779. serializationObject.gravity = this.gravity.asArray();
  56780. serializationObject.color1 = this.color1.asArray();
  56781. serializationObject.color2 = this.color2.asArray();
  56782. serializationObject.colorDead = this.colorDead.asArray();
  56783. serializationObject.updateSpeed = this.updateSpeed;
  56784. serializationObject.targetStopDuration = this.targetStopDuration;
  56785. serializationObject.blendMode = this.blendMode;
  56786. // Emitter
  56787. if (this.particleEmitterType) {
  56788. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56789. }
  56790. return serializationObject;
  56791. };
  56792. /**
  56793. * Parses a JSON object to create a GPU particle system.
  56794. * @param parsedParticleSystem The JSON object to parse
  56795. * @param scene The scene to create the particle system in
  56796. * @param rootUrl The root url to use to load external dependencies like texture
  56797. * @returns the parsed GPU particle system
  56798. */
  56799. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56800. var name = parsedParticleSystem.name;
  56801. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56802. if (parsedParticleSystem.id) {
  56803. particleSystem.id = parsedParticleSystem.id;
  56804. }
  56805. // Texture
  56806. if (parsedParticleSystem.textureName) {
  56807. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56808. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56809. }
  56810. // Emitter
  56811. if (parsedParticleSystem.emitterId) {
  56812. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56813. }
  56814. else {
  56815. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56816. }
  56817. // Animations
  56818. if (parsedParticleSystem.animations) {
  56819. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56820. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56821. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56822. }
  56823. }
  56824. // Particle system
  56825. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  56826. particleSystem.minSize = parsedParticleSystem.minSize;
  56827. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56828. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56829. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56830. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56831. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56832. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56833. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56834. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56835. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56836. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56837. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56838. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56839. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56840. // Emitter
  56841. if (parsedParticleSystem.particleEmitterType) {
  56842. var emitterType = void 0;
  56843. switch (parsedParticleSystem.particleEmitterType.type) {
  56844. case "SphereEmitter":
  56845. emitterType = new BABYLON.SphereParticleEmitter();
  56846. break;
  56847. case "SphereDirectedParticleEmitter":
  56848. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56849. break;
  56850. case "ConeEmitter":
  56851. emitterType = new BABYLON.ConeParticleEmitter();
  56852. break;
  56853. case "BoxEmitter":
  56854. default:
  56855. emitterType = new BABYLON.BoxParticleEmitter();
  56856. break;
  56857. }
  56858. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56859. particleSystem.particleEmitterType = emitterType;
  56860. }
  56861. return particleSystem;
  56862. };
  56863. return GPUParticleSystem;
  56864. }());
  56865. BABYLON.GPUParticleSystem = GPUParticleSystem;
  56866. })(BABYLON || (BABYLON = {}));
  56867. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  56868. "use strict";
  56869. var BABYLON;
  56870. (function (BABYLON) {
  56871. /**
  56872. * Represents one particle of a solid particle system.
  56873. */
  56874. var SolidParticle = /** @class */ (function () {
  56875. /**
  56876. * Creates a Solid Particle object.
  56877. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  56878. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56879. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56880. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56881. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56882. * @param shapeId (integer) is the model shape identifier in the SPS.
  56883. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56884. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56885. */
  56886. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56887. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56888. /**
  56889. * particle global index
  56890. */
  56891. this.idx = 0;
  56892. /**
  56893. * The color of the particle
  56894. */
  56895. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56896. /**
  56897. * The world space position of the particle.
  56898. */
  56899. this.position = BABYLON.Vector3.Zero();
  56900. /**
  56901. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56902. */
  56903. this.rotation = BABYLON.Vector3.Zero();
  56904. /**
  56905. * The scaling of the particle.
  56906. */
  56907. this.scaling = BABYLON.Vector3.One();
  56908. /**
  56909. * The uvs of the particle.
  56910. */
  56911. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56912. /**
  56913. * The current speed of the particle.
  56914. */
  56915. this.velocity = BABYLON.Vector3.Zero();
  56916. /**
  56917. * The pivot point in the particle local space.
  56918. */
  56919. this.pivot = BABYLON.Vector3.Zero();
  56920. /**
  56921. * Must the particle be translated from its pivot point in its local space ?
  56922. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56923. * Default : false
  56924. */
  56925. this.translateFromPivot = false;
  56926. /**
  56927. * Is the particle active or not ?
  56928. */
  56929. this.alive = true;
  56930. /**
  56931. * Is the particle visible or not ?
  56932. */
  56933. this.isVisible = true;
  56934. /**
  56935. * Index of this particle in the global "positions" array (Internal use)
  56936. */
  56937. this._pos = 0;
  56938. /**
  56939. * Index of this particle in the global "indices" array (Internal use)
  56940. */
  56941. this._ind = 0;
  56942. /**
  56943. * ModelShape id of this particle
  56944. */
  56945. this.shapeId = 0;
  56946. /**
  56947. * Index of the particle in its shape id (Internal use)
  56948. */
  56949. this.idxInShape = 0;
  56950. /**
  56951. * Still set as invisible in order to skip useless computations (Internal use)
  56952. */
  56953. this._stillInvisible = false;
  56954. /**
  56955. * Last computed particle rotation matrix
  56956. */
  56957. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56958. /**
  56959. * Parent particle Id, if any.
  56960. * Default null.
  56961. */
  56962. this.parentId = null;
  56963. /**
  56964. * Internal global position in the SPS.
  56965. */
  56966. this._globalPosition = BABYLON.Vector3.Zero();
  56967. this.idx = particleIndex;
  56968. this._pos = positionIndex;
  56969. this._ind = indiceIndex;
  56970. this._model = model;
  56971. this.shapeId = shapeId;
  56972. this.idxInShape = idxInShape;
  56973. this._sps = sps;
  56974. if (modelBoundingInfo) {
  56975. this._modelBoundingInfo = modelBoundingInfo;
  56976. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56977. }
  56978. }
  56979. Object.defineProperty(SolidParticle.prototype, "scale", {
  56980. /**
  56981. * Legacy support, changed scale to scaling
  56982. */
  56983. get: function () {
  56984. return this.scaling;
  56985. },
  56986. /**
  56987. * Legacy support, changed scale to scaling
  56988. */
  56989. set: function (scale) {
  56990. this.scaling = scale;
  56991. },
  56992. enumerable: true,
  56993. configurable: true
  56994. });
  56995. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56996. /**
  56997. * Legacy support, changed quaternion to rotationQuaternion
  56998. */
  56999. get: function () {
  57000. return this.rotationQuaternion;
  57001. },
  57002. /**
  57003. * Legacy support, changed quaternion to rotationQuaternion
  57004. */
  57005. set: function (q) {
  57006. this.rotationQuaternion = q;
  57007. },
  57008. enumerable: true,
  57009. configurable: true
  57010. });
  57011. /**
  57012. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57013. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57014. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57015. * @returns true if it intersects
  57016. */
  57017. SolidParticle.prototype.intersectsMesh = function (target) {
  57018. if (!this._boundingInfo || !target._boundingInfo) {
  57019. return false;
  57020. }
  57021. if (this._sps._bSphereOnly) {
  57022. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57023. }
  57024. return this._boundingInfo.intersects(target._boundingInfo, false);
  57025. };
  57026. return SolidParticle;
  57027. }());
  57028. BABYLON.SolidParticle = SolidParticle;
  57029. /**
  57030. * Represents the shape of the model used by one particle of a solid particle system.
  57031. * SPS internal tool, don't use it manually.
  57032. */
  57033. var ModelShape = /** @class */ (function () {
  57034. /**
  57035. * 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.
  57036. * SPS internal tool, don't use it manually.
  57037. * @ignore
  57038. */
  57039. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57040. /**
  57041. * length of the shape in the model indices array (internal use)
  57042. */
  57043. this._indicesLength = 0;
  57044. this.shapeID = id;
  57045. this._shape = shape;
  57046. this._indicesLength = indicesLength;
  57047. this._shapeUV = shapeUV;
  57048. this._positionFunction = posFunction;
  57049. this._vertexFunction = vtxFunction;
  57050. }
  57051. return ModelShape;
  57052. }());
  57053. BABYLON.ModelShape = ModelShape;
  57054. /**
  57055. * Represents a Depth Sorted Particle in the solid particle system.
  57056. */
  57057. var DepthSortedParticle = /** @class */ (function () {
  57058. function DepthSortedParticle() {
  57059. /**
  57060. * Index of the particle in the "indices" array
  57061. */
  57062. this.ind = 0;
  57063. /**
  57064. * Length of the particle shape in the "indices" array
  57065. */
  57066. this.indicesLength = 0;
  57067. /**
  57068. * Squared distance from the particle to the camera
  57069. */
  57070. this.sqDistance = 0.0;
  57071. }
  57072. return DepthSortedParticle;
  57073. }());
  57074. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57075. })(BABYLON || (BABYLON = {}));
  57076. //# sourceMappingURL=babylon.solidParticle.js.map
  57077. "use strict";
  57078. var BABYLON;
  57079. (function (BABYLON) {
  57080. /**
  57081. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57082. *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.
  57083. * The SPS is also a particle system. It provides some methods to manage the particles.
  57084. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57085. *
  57086. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57087. */
  57088. var SolidParticleSystem = /** @class */ (function () {
  57089. /**
  57090. * Creates a SPS (Solid Particle System) object.
  57091. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57092. * @param scene (Scene) is the scene in which the SPS is added.
  57093. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57094. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57095. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57096. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57097. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57098. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57099. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57100. */
  57101. function SolidParticleSystem(name, scene, options) {
  57102. /**
  57103. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57104. * Example : var p = SPS.particles[i];
  57105. */
  57106. this.particles = new Array();
  57107. /**
  57108. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57109. */
  57110. this.nbParticles = 0;
  57111. /**
  57112. * If the particles must ever face the camera (default false). Useful for planar particles.
  57113. */
  57114. this.billboard = false;
  57115. /**
  57116. * Recompute normals when adding a shape
  57117. */
  57118. this.recomputeNormals = true;
  57119. /**
  57120. * This a counter ofr your own usage. It's not set by any SPS functions.
  57121. */
  57122. this.counter = 0;
  57123. /**
  57124. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57125. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57126. */
  57127. this.vars = {};
  57128. /**
  57129. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57130. */
  57131. this._bSphereOnly = false;
  57132. /**
  57133. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57134. */
  57135. this._bSphereRadiusFactor = 1.0;
  57136. this._positions = new Array();
  57137. this._indices = new Array();
  57138. this._normals = new Array();
  57139. this._colors = new Array();
  57140. this._uvs = new Array();
  57141. this._index = 0; // indices index
  57142. this._updatable = true;
  57143. this._pickable = false;
  57144. this._isVisibilityBoxLocked = false;
  57145. this._alwaysVisible = false;
  57146. this._depthSort = false;
  57147. this._shapeCounter = 0;
  57148. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57149. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57150. this._computeParticleColor = true;
  57151. this._computeParticleTexture = true;
  57152. this._computeParticleRotation = true;
  57153. this._computeParticleVertex = false;
  57154. this._computeBoundingBox = false;
  57155. this._depthSortParticles = true;
  57156. this._cam_axisZ = BABYLON.Vector3.Zero();
  57157. this._cam_axisY = BABYLON.Vector3.Zero();
  57158. this._cam_axisX = BABYLON.Vector3.Zero();
  57159. this._axisZ = BABYLON.Axis.Z;
  57160. this._camDir = BABYLON.Vector3.Zero();
  57161. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57162. this._rotMatrix = new BABYLON.Matrix();
  57163. this._invertMatrix = new BABYLON.Matrix();
  57164. this._rotated = BABYLON.Vector3.Zero();
  57165. this._quaternion = new BABYLON.Quaternion();
  57166. this._vertex = BABYLON.Vector3.Zero();
  57167. this._normal = BABYLON.Vector3.Zero();
  57168. this._yaw = 0.0;
  57169. this._pitch = 0.0;
  57170. this._roll = 0.0;
  57171. this._halfroll = 0.0;
  57172. this._halfpitch = 0.0;
  57173. this._halfyaw = 0.0;
  57174. this._sinRoll = 0.0;
  57175. this._cosRoll = 0.0;
  57176. this._sinPitch = 0.0;
  57177. this._cosPitch = 0.0;
  57178. this._sinYaw = 0.0;
  57179. this._cosYaw = 0.0;
  57180. this._mustUnrotateFixedNormals = false;
  57181. this._minimum = BABYLON.Vector3.Zero();
  57182. this._maximum = BABYLON.Vector3.Zero();
  57183. this._minBbox = BABYLON.Vector3.Zero();
  57184. this._maxBbox = BABYLON.Vector3.Zero();
  57185. this._particlesIntersect = false;
  57186. this._depthSortFunction = function (p1, p2) {
  57187. return (p2.sqDistance - p1.sqDistance);
  57188. };
  57189. this._needs32Bits = false;
  57190. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57191. this._scaledPivot = BABYLON.Vector3.Zero();
  57192. this._particleHasParent = false;
  57193. this.name = name;
  57194. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57195. this._camera = scene.activeCamera;
  57196. this._pickable = options ? options.isPickable : false;
  57197. this._depthSort = options ? options.enableDepthSort : false;
  57198. this._particlesIntersect = options ? options.particleIntersection : false;
  57199. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57200. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57201. if (options && options.updatable) {
  57202. this._updatable = options.updatable;
  57203. }
  57204. else {
  57205. this._updatable = true;
  57206. }
  57207. if (this._pickable) {
  57208. this.pickedParticles = [];
  57209. }
  57210. if (this._depthSort) {
  57211. this.depthSortedParticles = [];
  57212. }
  57213. }
  57214. /**
  57215. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57216. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57217. * @returns the created mesh
  57218. */
  57219. SolidParticleSystem.prototype.buildMesh = function () {
  57220. if (this.nbParticles === 0) {
  57221. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57222. this.addShape(triangle, 1);
  57223. triangle.dispose();
  57224. }
  57225. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57226. this._positions32 = new Float32Array(this._positions);
  57227. this._uvs32 = new Float32Array(this._uvs);
  57228. this._colors32 = new Float32Array(this._colors);
  57229. if (this.recomputeNormals) {
  57230. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57231. }
  57232. this._normals32 = new Float32Array(this._normals);
  57233. this._fixedNormal32 = new Float32Array(this._normals);
  57234. if (this._mustUnrotateFixedNormals) {
  57235. this._unrotateFixedNormals();
  57236. }
  57237. var vertexData = new BABYLON.VertexData();
  57238. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57239. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57240. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57241. if (this._uvs32) {
  57242. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57243. ;
  57244. }
  57245. if (this._colors32) {
  57246. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57247. }
  57248. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57249. vertexData.applyToMesh(mesh, this._updatable);
  57250. this.mesh = mesh;
  57251. this.mesh.isPickable = this._pickable;
  57252. // free memory
  57253. if (!this._depthSort) {
  57254. this._indices = null;
  57255. }
  57256. this._positions = null;
  57257. this._normals = null;
  57258. this._uvs = null;
  57259. this._colors = null;
  57260. if (!this._updatable) {
  57261. this.particles.length = 0;
  57262. }
  57263. return mesh;
  57264. };
  57265. /**
  57266. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57267. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57268. * Thus the particles generated from `digest()` have their property `position` set yet.
  57269. * @param mesh ( Mesh ) is the mesh to be digested
  57270. * @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
  57271. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57272. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57273. * @returns the current SPS
  57274. */
  57275. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57276. var size = (options && options.facetNb) || 1;
  57277. var number = (options && options.number) || 0;
  57278. var delta = (options && options.delta) || 0;
  57279. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57280. var meshInd = mesh.getIndices();
  57281. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57282. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57283. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57284. var f = 0; // facet counter
  57285. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57286. // compute size from number
  57287. if (number) {
  57288. number = (number > totalFacets) ? totalFacets : number;
  57289. size = Math.round(totalFacets / number);
  57290. delta = 0;
  57291. }
  57292. else {
  57293. size = (size > totalFacets) ? totalFacets : size;
  57294. }
  57295. var facetPos = []; // submesh positions
  57296. var facetInd = []; // submesh indices
  57297. var facetUV = []; // submesh UV
  57298. var facetCol = []; // submesh colors
  57299. var barycenter = BABYLON.Vector3.Zero();
  57300. var sizeO = size;
  57301. while (f < totalFacets) {
  57302. size = sizeO + Math.floor((1 + delta) * Math.random());
  57303. if (f > totalFacets - size) {
  57304. size = totalFacets - f;
  57305. }
  57306. // reset temp arrays
  57307. facetPos.length = 0;
  57308. facetInd.length = 0;
  57309. facetUV.length = 0;
  57310. facetCol.length = 0;
  57311. // iterate over "size" facets
  57312. var fi = 0;
  57313. for (var j = f * 3; j < (f + size) * 3; j++) {
  57314. facetInd.push(fi);
  57315. var i = meshInd[j];
  57316. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57317. if (meshUV) {
  57318. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57319. }
  57320. if (meshCol) {
  57321. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57322. }
  57323. fi++;
  57324. }
  57325. // create a model shape for each single particle
  57326. var idx = this.nbParticles;
  57327. var shape = this._posToShape(facetPos);
  57328. var shapeUV = this._uvsToShapeUV(facetUV);
  57329. // compute the barycenter of the shape
  57330. var v;
  57331. for (v = 0; v < shape.length; v++) {
  57332. barycenter.addInPlace(shape[v]);
  57333. }
  57334. barycenter.scaleInPlace(1 / shape.length);
  57335. // shift the shape from its barycenter to the origin
  57336. for (v = 0; v < shape.length; v++) {
  57337. shape[v].subtractInPlace(barycenter);
  57338. }
  57339. var bInfo;
  57340. if (this._particlesIntersect) {
  57341. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57342. }
  57343. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57344. // add the particle in the SPS
  57345. var currentPos = this._positions.length;
  57346. var currentInd = this._indices.length;
  57347. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57348. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57349. // initialize the particle position
  57350. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57351. this._index += shape.length;
  57352. idx++;
  57353. this.nbParticles++;
  57354. this._shapeCounter++;
  57355. f += size;
  57356. }
  57357. return this;
  57358. };
  57359. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57360. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57361. var index = 0;
  57362. var idx = 0;
  57363. for (var p = 0; p < this.particles.length; p++) {
  57364. this._particle = this.particles[p];
  57365. this._shape = this._particle._model._shape;
  57366. if (this._particle.rotationQuaternion) {
  57367. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57368. }
  57369. else {
  57370. this._yaw = this._particle.rotation.y;
  57371. this._pitch = this._particle.rotation.x;
  57372. this._roll = this._particle.rotation.z;
  57373. this._quaternionRotationYPR();
  57374. }
  57375. this._quaternionToRotationMatrix();
  57376. this._rotMatrix.invertToRef(this._invertMatrix);
  57377. for (var pt = 0; pt < this._shape.length; pt++) {
  57378. idx = index + pt * 3;
  57379. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57380. this._fixedNormal32[idx] = this._normal.x;
  57381. this._fixedNormal32[idx + 1] = this._normal.y;
  57382. this._fixedNormal32[idx + 2] = this._normal.z;
  57383. }
  57384. index = idx + 3;
  57385. }
  57386. };
  57387. //reset copy
  57388. SolidParticleSystem.prototype._resetCopy = function () {
  57389. this._copy.position.x = 0;
  57390. this._copy.position.y = 0;
  57391. this._copy.position.z = 0;
  57392. this._copy.rotation.x = 0;
  57393. this._copy.rotation.y = 0;
  57394. this._copy.rotation.z = 0;
  57395. this._copy.rotationQuaternion = null;
  57396. this._copy.scaling.x = 1.0;
  57397. this._copy.scaling.y = 1.0;
  57398. this._copy.scaling.z = 1.0;
  57399. this._copy.uvs.x = 0;
  57400. this._copy.uvs.y = 0;
  57401. this._copy.uvs.z = 1.0;
  57402. this._copy.uvs.w = 1.0;
  57403. this._copy.color = null;
  57404. this._copy.translateFromPivot = false;
  57405. };
  57406. // _meshBuilder : inserts the shape model in the global SPS mesh
  57407. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57408. var i;
  57409. var u = 0;
  57410. var c = 0;
  57411. var n = 0;
  57412. this._resetCopy();
  57413. if (options && options.positionFunction) {
  57414. options.positionFunction(this._copy, idx, idxInShape);
  57415. this._mustUnrotateFixedNormals = true;
  57416. }
  57417. if (this._copy.rotationQuaternion) {
  57418. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57419. }
  57420. else {
  57421. this._yaw = this._copy.rotation.y;
  57422. this._pitch = this._copy.rotation.x;
  57423. this._roll = this._copy.rotation.z;
  57424. this._quaternionRotationYPR();
  57425. }
  57426. this._quaternionToRotationMatrix();
  57427. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57428. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57429. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57430. if (this._copy.translateFromPivot) {
  57431. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57432. }
  57433. else {
  57434. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57435. }
  57436. for (i = 0; i < shape.length; i++) {
  57437. this._vertex.x = shape[i].x;
  57438. this._vertex.y = shape[i].y;
  57439. this._vertex.z = shape[i].z;
  57440. if (options && options.vertexFunction) {
  57441. options.vertexFunction(this._copy, this._vertex, i);
  57442. }
  57443. this._vertex.x *= this._copy.scaling.x;
  57444. this._vertex.y *= this._copy.scaling.y;
  57445. this._vertex.z *= this._copy.scaling.z;
  57446. this._vertex.x -= this._scaledPivot.x;
  57447. this._vertex.y -= this._scaledPivot.y;
  57448. this._vertex.z -= this._scaledPivot.z;
  57449. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57450. this._rotated.addInPlace(this._pivotBackTranslation);
  57451. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57452. if (meshUV) {
  57453. 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);
  57454. u += 2;
  57455. }
  57456. if (this._copy.color) {
  57457. this._color = this._copy.color;
  57458. }
  57459. else if (meshCol && meshCol[c] !== undefined) {
  57460. this._color.r = meshCol[c];
  57461. this._color.g = meshCol[c + 1];
  57462. this._color.b = meshCol[c + 2];
  57463. this._color.a = meshCol[c + 3];
  57464. }
  57465. else {
  57466. this._color.r = 1.0;
  57467. this._color.g = 1.0;
  57468. this._color.b = 1.0;
  57469. this._color.a = 1.0;
  57470. }
  57471. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57472. c += 4;
  57473. if (!this.recomputeNormals && meshNor) {
  57474. this._normal.x = meshNor[n];
  57475. this._normal.y = meshNor[n + 1];
  57476. this._normal.z = meshNor[n + 2];
  57477. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57478. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57479. n += 3;
  57480. }
  57481. }
  57482. for (i = 0; i < meshInd.length; i++) {
  57483. var current_ind = p + meshInd[i];
  57484. indices.push(current_ind);
  57485. if (current_ind > 65535) {
  57486. this._needs32Bits = true;
  57487. }
  57488. }
  57489. if (this._pickable) {
  57490. var nbfaces = meshInd.length / 3;
  57491. for (i = 0; i < nbfaces; i++) {
  57492. this.pickedParticles.push({ idx: idx, faceId: i });
  57493. }
  57494. }
  57495. if (this._depthSort) {
  57496. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57497. }
  57498. return this._copy;
  57499. };
  57500. // returns a shape array from positions array
  57501. SolidParticleSystem.prototype._posToShape = function (positions) {
  57502. var shape = [];
  57503. for (var i = 0; i < positions.length; i += 3) {
  57504. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57505. }
  57506. return shape;
  57507. };
  57508. // returns a shapeUV array from a Vector4 uvs
  57509. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57510. var shapeUV = [];
  57511. if (uvs) {
  57512. for (var i = 0; i < uvs.length; i++)
  57513. shapeUV.push(uvs[i]);
  57514. }
  57515. return shapeUV;
  57516. };
  57517. // adds a new particle object in the particles array
  57518. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57519. if (bInfo === void 0) { bInfo = null; }
  57520. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57521. this.particles.push(sp);
  57522. return sp;
  57523. };
  57524. /**
  57525. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57526. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57527. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57528. * @param nb (positive integer) the number of particles to be created from this model
  57529. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57530. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57531. * @returns the number of shapes in the system
  57532. */
  57533. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57534. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57535. var meshInd = mesh.getIndices();
  57536. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57537. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57538. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57539. var bbInfo;
  57540. if (this._particlesIntersect) {
  57541. bbInfo = mesh.getBoundingInfo();
  57542. }
  57543. var shape = this._posToShape(meshPos);
  57544. var shapeUV = this._uvsToShapeUV(meshUV);
  57545. var posfunc = options ? options.positionFunction : null;
  57546. var vtxfunc = options ? options.vertexFunction : null;
  57547. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57548. // particles
  57549. var sp;
  57550. var currentCopy;
  57551. var idx = this.nbParticles;
  57552. for (var i = 0; i < nb; i++) {
  57553. var currentPos = this._positions.length;
  57554. var currentInd = this._indices.length;
  57555. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57556. if (this._updatable) {
  57557. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57558. sp.position.copyFrom(currentCopy.position);
  57559. sp.rotation.copyFrom(currentCopy.rotation);
  57560. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57561. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57562. }
  57563. if (currentCopy.color && sp.color) {
  57564. sp.color.copyFrom(currentCopy.color);
  57565. }
  57566. sp.scaling.copyFrom(currentCopy.scaling);
  57567. sp.uvs.copyFrom(currentCopy.uvs);
  57568. }
  57569. this._index += shape.length;
  57570. idx++;
  57571. }
  57572. this.nbParticles += nb;
  57573. this._shapeCounter++;
  57574. return this._shapeCounter - 1;
  57575. };
  57576. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57577. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57578. this._resetCopy();
  57579. if (particle._model._positionFunction) {
  57580. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57581. }
  57582. if (this._copy.rotationQuaternion) {
  57583. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57584. }
  57585. else {
  57586. this._yaw = this._copy.rotation.y;
  57587. this._pitch = this._copy.rotation.x;
  57588. this._roll = this._copy.rotation.z;
  57589. this._quaternionRotationYPR();
  57590. }
  57591. this._quaternionToRotationMatrix();
  57592. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57593. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57594. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57595. if (this._copy.translateFromPivot) {
  57596. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57597. }
  57598. else {
  57599. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57600. }
  57601. this._shape = particle._model._shape;
  57602. for (var pt = 0; pt < this._shape.length; pt++) {
  57603. this._vertex.x = this._shape[pt].x;
  57604. this._vertex.y = this._shape[pt].y;
  57605. this._vertex.z = this._shape[pt].z;
  57606. if (particle._model._vertexFunction) {
  57607. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57608. }
  57609. this._vertex.x *= this._copy.scaling.x;
  57610. this._vertex.y *= this._copy.scaling.y;
  57611. this._vertex.z *= this._copy.scaling.z;
  57612. this._vertex.x -= this._scaledPivot.x;
  57613. this._vertex.y -= this._scaledPivot.y;
  57614. this._vertex.z -= this._scaledPivot.z;
  57615. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57616. this._rotated.addInPlace(this._pivotBackTranslation);
  57617. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57618. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57619. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57620. }
  57621. particle.position.x = 0.0;
  57622. particle.position.y = 0.0;
  57623. particle.position.z = 0.0;
  57624. particle.rotation.x = 0.0;
  57625. particle.rotation.y = 0.0;
  57626. particle.rotation.z = 0.0;
  57627. particle.rotationQuaternion = null;
  57628. particle.scaling.x = 1.0;
  57629. particle.scaling.y = 1.0;
  57630. particle.scaling.z = 1.0;
  57631. particle.uvs.x = 0.0;
  57632. particle.uvs.y = 0.0;
  57633. particle.uvs.z = 1.0;
  57634. particle.uvs.w = 1.0;
  57635. particle.pivot.x = 0.0;
  57636. particle.pivot.y = 0.0;
  57637. particle.pivot.z = 0.0;
  57638. particle.translateFromPivot = false;
  57639. particle.parentId = null;
  57640. };
  57641. /**
  57642. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57643. * @returns the SPS.
  57644. */
  57645. SolidParticleSystem.prototype.rebuildMesh = function () {
  57646. for (var p = 0; p < this.particles.length; p++) {
  57647. this._rebuildParticle(this.particles[p]);
  57648. }
  57649. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57650. return this;
  57651. };
  57652. /**
  57653. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57654. * This method calls `updateParticle()` for each particle of the SPS.
  57655. * For an animated SPS, it is usually called within the render loop.
  57656. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57657. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57658. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57659. * @returns the SPS.
  57660. */
  57661. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57662. if (start === void 0) { start = 0; }
  57663. if (end === void 0) { end = this.nbParticles - 1; }
  57664. if (update === void 0) { update = true; }
  57665. if (!this._updatable) {
  57666. return this;
  57667. }
  57668. // custom beforeUpdate
  57669. this.beforeUpdateParticles(start, end, update);
  57670. this._cam_axisX.x = 1.0;
  57671. this._cam_axisX.y = 0.0;
  57672. this._cam_axisX.z = 0.0;
  57673. this._cam_axisY.x = 0.0;
  57674. this._cam_axisY.y = 1.0;
  57675. this._cam_axisY.z = 0.0;
  57676. this._cam_axisZ.x = 0.0;
  57677. this._cam_axisZ.y = 0.0;
  57678. this._cam_axisZ.z = 1.0;
  57679. // cases when the World Matrix is to be computed first
  57680. if (this.billboard || this._depthSort) {
  57681. this.mesh.computeWorldMatrix(true);
  57682. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57683. }
  57684. // if the particles will always face the camera
  57685. if (this.billboard) {
  57686. // compute the camera position and un-rotate it by the current mesh rotation
  57687. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57688. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57689. this._cam_axisZ.normalize();
  57690. // same for camera up vector extracted from the cam view matrix
  57691. var view = this._camera.getViewMatrix(true);
  57692. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57693. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57694. this._cam_axisY.normalize();
  57695. this._cam_axisX.normalize();
  57696. }
  57697. // if depthSort, compute the camera global position in the mesh local system
  57698. if (this._depthSort) {
  57699. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57700. }
  57701. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57702. var idx = 0; // current position index in the global array positions32
  57703. var index = 0; // position start index in the global array positions32 of the current particle
  57704. var colidx = 0; // current color index in the global array colors32
  57705. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57706. var uvidx = 0; // current uv index in the global array uvs32
  57707. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57708. var pt = 0; // current index in the particle model shape
  57709. if (this.mesh.isFacetDataEnabled) {
  57710. this._computeBoundingBox = true;
  57711. }
  57712. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57713. if (this._computeBoundingBox) {
  57714. if (start == 0 && end == this.nbParticles - 1) {
  57715. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57716. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57717. }
  57718. else {
  57719. if (this.mesh._boundingInfo) {
  57720. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57721. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57722. }
  57723. }
  57724. }
  57725. // particle loop
  57726. index = this.particles[start]._pos;
  57727. var vpos = (index / 3) | 0;
  57728. colorIndex = vpos * 4;
  57729. uvIndex = vpos * 2;
  57730. for (var p = start; p <= end; p++) {
  57731. this._particle = this.particles[p];
  57732. this._shape = this._particle._model._shape;
  57733. this._shapeUV = this._particle._model._shapeUV;
  57734. // call to custom user function to update the particle properties
  57735. this.updateParticle(this._particle);
  57736. // camera-particle distance for depth sorting
  57737. if (this._depthSort && this._depthSortParticles) {
  57738. var dsp = this.depthSortedParticles[p];
  57739. dsp.ind = this._particle._ind;
  57740. dsp.indicesLength = this._particle._model._indicesLength;
  57741. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57742. }
  57743. // skip the computations for inactive or already invisible particles
  57744. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57745. // increment indexes for the next particle
  57746. pt = this._shape.length;
  57747. index += pt * 3;
  57748. colorIndex += pt * 4;
  57749. uvIndex += pt * 2;
  57750. continue;
  57751. }
  57752. if (this._particle.isVisible) {
  57753. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57754. this._particleHasParent = (this._particle.parentId !== null);
  57755. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57756. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57757. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57758. // particle rotation matrix
  57759. if (this.billboard) {
  57760. this._particle.rotation.x = 0.0;
  57761. this._particle.rotation.y = 0.0;
  57762. }
  57763. if (this._computeParticleRotation || this.billboard) {
  57764. if (this._particle.rotationQuaternion) {
  57765. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57766. }
  57767. else {
  57768. this._yaw = this._particle.rotation.y;
  57769. this._pitch = this._particle.rotation.x;
  57770. this._roll = this._particle.rotation.z;
  57771. this._quaternionRotationYPR();
  57772. }
  57773. this._quaternionToRotationMatrix();
  57774. }
  57775. if (this._particleHasParent) {
  57776. this._parent = this.particles[this._particle.parentId];
  57777. 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];
  57778. 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];
  57779. 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];
  57780. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57781. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57782. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57783. if (this._computeParticleRotation || this.billboard) {
  57784. 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];
  57785. 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];
  57786. 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];
  57787. 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];
  57788. 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];
  57789. 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];
  57790. 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];
  57791. 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];
  57792. 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];
  57793. }
  57794. }
  57795. else {
  57796. this._particle._globalPosition.x = this._particle.position.x;
  57797. this._particle._globalPosition.y = this._particle.position.y;
  57798. this._particle._globalPosition.z = this._particle.position.z;
  57799. if (this._computeParticleRotation || this.billboard) {
  57800. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57801. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57802. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57803. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57804. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57805. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57806. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57807. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57808. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57809. }
  57810. }
  57811. if (this._particle.translateFromPivot) {
  57812. this._pivotBackTranslation.x = 0.0;
  57813. this._pivotBackTranslation.y = 0.0;
  57814. this._pivotBackTranslation.z = 0.0;
  57815. }
  57816. else {
  57817. this._pivotBackTranslation.x = this._scaledPivot.x;
  57818. this._pivotBackTranslation.y = this._scaledPivot.y;
  57819. this._pivotBackTranslation.z = this._scaledPivot.z;
  57820. }
  57821. // particle vertex loop
  57822. for (pt = 0; pt < this._shape.length; pt++) {
  57823. idx = index + pt * 3;
  57824. colidx = colorIndex + pt * 4;
  57825. uvidx = uvIndex + pt * 2;
  57826. this._vertex.x = this._shape[pt].x;
  57827. this._vertex.y = this._shape[pt].y;
  57828. this._vertex.z = this._shape[pt].z;
  57829. if (this._computeParticleVertex) {
  57830. this.updateParticleVertex(this._particle, this._vertex, pt);
  57831. }
  57832. // positions
  57833. this._vertex.x *= this._particle.scaling.x;
  57834. this._vertex.y *= this._particle.scaling.y;
  57835. this._vertex.z *= this._particle.scaling.z;
  57836. this._vertex.x -= this._scaledPivot.x;
  57837. this._vertex.y -= this._scaledPivot.y;
  57838. this._vertex.z -= this._scaledPivot.z;
  57839. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57840. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57841. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57842. this._rotated.x += this._pivotBackTranslation.x;
  57843. this._rotated.y += this._pivotBackTranslation.y;
  57844. this._rotated.z += this._pivotBackTranslation.z;
  57845. 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;
  57846. 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;
  57847. 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;
  57848. if (this._computeBoundingBox) {
  57849. if (this._positions32[idx] < this._minimum.x) {
  57850. this._minimum.x = this._positions32[idx];
  57851. }
  57852. if (this._positions32[idx] > this._maximum.x) {
  57853. this._maximum.x = this._positions32[idx];
  57854. }
  57855. if (this._positions32[idx + 1] < this._minimum.y) {
  57856. this._minimum.y = this._positions32[idx + 1];
  57857. }
  57858. if (this._positions32[idx + 1] > this._maximum.y) {
  57859. this._maximum.y = this._positions32[idx + 1];
  57860. }
  57861. if (this._positions32[idx + 2] < this._minimum.z) {
  57862. this._minimum.z = this._positions32[idx + 2];
  57863. }
  57864. if (this._positions32[idx + 2] > this._maximum.z) {
  57865. this._maximum.z = this._positions32[idx + 2];
  57866. }
  57867. }
  57868. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  57869. if (!this._computeParticleVertex) {
  57870. this._normal.x = this._fixedNormal32[idx];
  57871. this._normal.y = this._fixedNormal32[idx + 1];
  57872. this._normal.z = this._fixedNormal32[idx + 2];
  57873. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  57874. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  57875. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  57876. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57877. 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;
  57878. 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;
  57879. }
  57880. if (this._computeParticleColor && this._particle.color) {
  57881. this._colors32[colidx] = this._particle.color.r;
  57882. this._colors32[colidx + 1] = this._particle.color.g;
  57883. this._colors32[colidx + 2] = this._particle.color.b;
  57884. this._colors32[colidx + 3] = this._particle.color.a;
  57885. }
  57886. if (this._computeParticleTexture) {
  57887. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57888. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57889. }
  57890. }
  57891. }
  57892. else {
  57893. this._particle._stillInvisible = true; // mark the particle as invisible
  57894. for (pt = 0; pt < this._shape.length; pt++) {
  57895. idx = index + pt * 3;
  57896. colidx = colorIndex + pt * 4;
  57897. uvidx = uvIndex + pt * 2;
  57898. this._positions32[idx] = 0.0;
  57899. this._positions32[idx + 1] = 0.0;
  57900. this._positions32[idx + 2] = 0.0;
  57901. this._normals32[idx] = 0.0;
  57902. this._normals32[idx + 1] = 0.0;
  57903. this._normals32[idx + 2] = 0.0;
  57904. if (this._computeParticleColor && this._particle.color) {
  57905. this._colors32[colidx] = this._particle.color.r;
  57906. this._colors32[colidx + 1] = this._particle.color.g;
  57907. this._colors32[colidx + 2] = this._particle.color.b;
  57908. this._colors32[colidx + 3] = this._particle.color.a;
  57909. }
  57910. if (this._computeParticleTexture) {
  57911. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57912. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57913. }
  57914. }
  57915. }
  57916. // if the particle intersections must be computed : update the bbInfo
  57917. if (this._particlesIntersect) {
  57918. var bInfo = this._particle._boundingInfo;
  57919. var bBox = bInfo.boundingBox;
  57920. var bSphere = bInfo.boundingSphere;
  57921. if (!this._bSphereOnly) {
  57922. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57923. for (var b = 0; b < bBox.vectors.length; b++) {
  57924. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57925. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57926. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57927. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57928. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57929. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57930. 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;
  57931. 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;
  57932. 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;
  57933. }
  57934. bBox._update(this.mesh._worldMatrix);
  57935. }
  57936. // place and scale the particle bouding sphere in the SPS local system, then update it
  57937. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57938. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57939. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57940. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57941. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57942. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57943. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57944. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57945. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57946. 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));
  57947. bSphere._update(this.mesh._worldMatrix);
  57948. }
  57949. // increment indexes for the next particle
  57950. index = idx + 3;
  57951. colorIndex = colidx + 4;
  57952. uvIndex = uvidx + 2;
  57953. }
  57954. // if the VBO must be updated
  57955. if (update) {
  57956. if (this._computeParticleColor) {
  57957. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57958. }
  57959. if (this._computeParticleTexture) {
  57960. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57961. }
  57962. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57963. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57964. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57965. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57966. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57967. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57968. for (var i = 0; i < this._normals32.length; i++) {
  57969. this._fixedNormal32[i] = this._normals32[i];
  57970. }
  57971. }
  57972. if (!this.mesh.areNormalsFrozen) {
  57973. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57974. }
  57975. }
  57976. if (this._depthSort && this._depthSortParticles) {
  57977. this.depthSortedParticles.sort(this._depthSortFunction);
  57978. var dspl = this.depthSortedParticles.length;
  57979. var sorted = 0;
  57980. var lind = 0;
  57981. var sind = 0;
  57982. var sid = 0;
  57983. for (sorted = 0; sorted < dspl; sorted++) {
  57984. lind = this.depthSortedParticles[sorted].indicesLength;
  57985. sind = this.depthSortedParticles[sorted].ind;
  57986. for (var i = 0; i < lind; i++) {
  57987. this._indices32[sid] = this._indices[sind + i];
  57988. sid++;
  57989. }
  57990. }
  57991. this.mesh.updateIndices(this._indices32);
  57992. }
  57993. }
  57994. if (this._computeBoundingBox) {
  57995. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57996. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57997. }
  57998. this.afterUpdateParticles(start, end, update);
  57999. return this;
  58000. };
  58001. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58002. this._halfroll = this._roll * 0.5;
  58003. this._halfpitch = this._pitch * 0.5;
  58004. this._halfyaw = this._yaw * 0.5;
  58005. this._sinRoll = Math.sin(this._halfroll);
  58006. this._cosRoll = Math.cos(this._halfroll);
  58007. this._sinPitch = Math.sin(this._halfpitch);
  58008. this._cosPitch = Math.cos(this._halfpitch);
  58009. this._sinYaw = Math.sin(this._halfyaw);
  58010. this._cosYaw = Math.cos(this._halfyaw);
  58011. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58012. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58013. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58014. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58015. };
  58016. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58017. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58018. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58019. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58020. this._rotMatrix.m[3] = 0;
  58021. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58022. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58023. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58024. this._rotMatrix.m[7] = 0;
  58025. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58026. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58027. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58028. this._rotMatrix.m[11] = 0;
  58029. this._rotMatrix.m[12] = 0;
  58030. this._rotMatrix.m[13] = 0;
  58031. this._rotMatrix.m[14] = 0;
  58032. this._rotMatrix.m[15] = 1.0;
  58033. };
  58034. /**
  58035. * Disposes the SPS.
  58036. */
  58037. SolidParticleSystem.prototype.dispose = function () {
  58038. this.mesh.dispose();
  58039. this.vars = null;
  58040. // drop references to internal big arrays for the GC
  58041. this._positions = null;
  58042. this._indices = null;
  58043. this._normals = null;
  58044. this._uvs = null;
  58045. this._colors = null;
  58046. this._indices32 = null;
  58047. this._positions32 = null;
  58048. this._normals32 = null;
  58049. this._fixedNormal32 = null;
  58050. this._uvs32 = null;
  58051. this._colors32 = null;
  58052. this.pickedParticles = null;
  58053. };
  58054. /**
  58055. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58056. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58057. * @returns the SPS.
  58058. */
  58059. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58060. if (!this._isVisibilityBoxLocked) {
  58061. this.mesh.refreshBoundingInfo();
  58062. }
  58063. return this;
  58064. };
  58065. /**
  58066. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58067. * @param size the size (float) of the visibility box
  58068. * note : this doesn't lock the SPS mesh bounding box.
  58069. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58070. */
  58071. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58072. var vis = size / 2;
  58073. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58074. };
  58075. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58076. /**
  58077. * Gets whether the SPS as always visible or not
  58078. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58079. */
  58080. get: function () {
  58081. return this._alwaysVisible;
  58082. },
  58083. /**
  58084. * Sets the SPS as always visible or not
  58085. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58086. */
  58087. set: function (val) {
  58088. this._alwaysVisible = val;
  58089. this.mesh.alwaysSelectAsActiveMesh = val;
  58090. },
  58091. enumerable: true,
  58092. configurable: true
  58093. });
  58094. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58095. /**
  58096. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58097. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58098. */
  58099. get: function () {
  58100. return this._isVisibilityBoxLocked;
  58101. },
  58102. /**
  58103. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58104. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58105. */
  58106. set: function (val) {
  58107. this._isVisibilityBoxLocked = val;
  58108. var boundingInfo = this.mesh.getBoundingInfo();
  58109. boundingInfo.isLocked = val;
  58110. },
  58111. enumerable: true,
  58112. configurable: true
  58113. });
  58114. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58115. /**
  58116. * Gets if `setParticles()` computes the particle rotations or not.
  58117. * Default value : true. The SPS is faster when it's set to false.
  58118. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58119. */
  58120. get: function () {
  58121. return this._computeParticleRotation;
  58122. },
  58123. /**
  58124. * Tells to `setParticles()` to compute the particle rotations or not.
  58125. * Default value : true. The SPS is faster when it's set to false.
  58126. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58127. */
  58128. set: function (val) {
  58129. this._computeParticleRotation = val;
  58130. },
  58131. enumerable: true,
  58132. configurable: true
  58133. });
  58134. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58135. /**
  58136. * Gets if `setParticles()` computes the particle colors or not.
  58137. * Default value : true. The SPS is faster when it's set to false.
  58138. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58139. */
  58140. get: function () {
  58141. return this._computeParticleColor;
  58142. },
  58143. /**
  58144. * Tells to `setParticles()` to compute the particle colors or not.
  58145. * Default value : true. The SPS is faster when it's set to false.
  58146. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58147. */
  58148. set: function (val) {
  58149. this._computeParticleColor = val;
  58150. },
  58151. enumerable: true,
  58152. configurable: true
  58153. });
  58154. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58155. /**
  58156. * Gets if `setParticles()` computes the particle textures or not.
  58157. * Default value : true. The SPS is faster when it's set to false.
  58158. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58159. */
  58160. get: function () {
  58161. return this._computeParticleTexture;
  58162. },
  58163. set: function (val) {
  58164. this._computeParticleTexture = val;
  58165. },
  58166. enumerable: true,
  58167. configurable: true
  58168. });
  58169. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58170. /**
  58171. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58172. * Default value : false. The SPS is faster when it's set to false.
  58173. * Note : the particle custom vertex positions aren't stored values.
  58174. */
  58175. get: function () {
  58176. return this._computeParticleVertex;
  58177. },
  58178. /**
  58179. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58180. * Default value : false. The SPS is faster when it's set to false.
  58181. * Note : the particle custom vertex positions aren't stored values.
  58182. */
  58183. set: function (val) {
  58184. this._computeParticleVertex = val;
  58185. },
  58186. enumerable: true,
  58187. configurable: true
  58188. });
  58189. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58190. /**
  58191. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58192. */
  58193. get: function () {
  58194. return this._computeBoundingBox;
  58195. },
  58196. /**
  58197. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58198. */
  58199. set: function (val) {
  58200. this._computeBoundingBox = val;
  58201. },
  58202. enumerable: true,
  58203. configurable: true
  58204. });
  58205. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58206. /**
  58207. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58208. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58209. * Default : `true`
  58210. */
  58211. get: function () {
  58212. return this._depthSortParticles;
  58213. },
  58214. /**
  58215. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58216. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58217. * Default : `true`
  58218. */
  58219. set: function (val) {
  58220. this._depthSortParticles = val;
  58221. },
  58222. enumerable: true,
  58223. configurable: true
  58224. });
  58225. // =======================================================================
  58226. // Particle behavior logic
  58227. // these following methods may be overwritten by the user to fit his needs
  58228. /**
  58229. * This function does nothing. It may be overwritten to set all the particle first values.
  58230. * The SPS doesn't call this function, you may have to call it by your own.
  58231. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58232. */
  58233. SolidParticleSystem.prototype.initParticles = function () {
  58234. };
  58235. /**
  58236. * This function does nothing. It may be overwritten to recycle a particle.
  58237. * The SPS doesn't call this function, you may have to call it by your own.
  58238. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58239. * @param particle The particle to recycle
  58240. * @returns the recycled particle
  58241. */
  58242. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58243. return particle;
  58244. };
  58245. /**
  58246. * Updates a particle : this function should be overwritten by the user.
  58247. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58248. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58249. * @example : just set a particle position or velocity and recycle conditions
  58250. * @param particle The particle to update
  58251. * @returns the updated particle
  58252. */
  58253. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58254. return particle;
  58255. };
  58256. /**
  58257. * Updates a vertex of a particle : it can be overwritten by the user.
  58258. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58259. * @param particle the current particle
  58260. * @param vertex the current index of the current particle
  58261. * @param pt the index of the current vertex in the particle shape
  58262. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58263. * @example : just set a vertex particle position
  58264. * @returns the updated vertex
  58265. */
  58266. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58267. return vertex;
  58268. };
  58269. /**
  58270. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58271. * This does nothing and may be overwritten by the user.
  58272. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58273. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58274. * @param update the boolean update value actually passed to setParticles()
  58275. */
  58276. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58277. };
  58278. /**
  58279. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58280. * This will be passed three parameters.
  58281. * This does nothing and may be overwritten by the user.
  58282. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58283. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58284. * @param update the boolean update value actually passed to setParticles()
  58285. */
  58286. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58287. };
  58288. return SolidParticleSystem;
  58289. }());
  58290. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58291. })(BABYLON || (BABYLON = {}));
  58292. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58293. "use strict";
  58294. var BABYLON;
  58295. (function (BABYLON) {
  58296. var ShaderMaterial = /** @class */ (function (_super) {
  58297. __extends(ShaderMaterial, _super);
  58298. function ShaderMaterial(name, scene, shaderPath, options) {
  58299. var _this = _super.call(this, name, scene) || this;
  58300. _this._textures = {};
  58301. _this._textureArrays = {};
  58302. _this._floats = {};
  58303. _this._ints = {};
  58304. _this._floatsArrays = {};
  58305. _this._colors3 = {};
  58306. _this._colors3Arrays = {};
  58307. _this._colors4 = {};
  58308. _this._vectors2 = {};
  58309. _this._vectors3 = {};
  58310. _this._vectors4 = {};
  58311. _this._matrices = {};
  58312. _this._matrices3x3 = {};
  58313. _this._matrices2x2 = {};
  58314. _this._vectors2Arrays = {};
  58315. _this._vectors3Arrays = {};
  58316. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58317. _this._shaderPath = shaderPath;
  58318. options.needAlphaBlending = options.needAlphaBlending || false;
  58319. options.needAlphaTesting = options.needAlphaTesting || false;
  58320. options.attributes = options.attributes || ["position", "normal", "uv"];
  58321. options.uniforms = options.uniforms || ["worldViewProjection"];
  58322. options.uniformBuffers = options.uniformBuffers || [];
  58323. options.samplers = options.samplers || [];
  58324. options.defines = options.defines || [];
  58325. _this._options = options;
  58326. return _this;
  58327. }
  58328. ShaderMaterial.prototype.getClassName = function () {
  58329. return "ShaderMaterial";
  58330. };
  58331. ShaderMaterial.prototype.needAlphaBlending = function () {
  58332. return this._options.needAlphaBlending;
  58333. };
  58334. ShaderMaterial.prototype.needAlphaTesting = function () {
  58335. return this._options.needAlphaTesting;
  58336. };
  58337. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58338. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58339. this._options.uniforms.push(uniformName);
  58340. }
  58341. };
  58342. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58343. if (this._options.samplers.indexOf(name) === -1) {
  58344. this._options.samplers.push(name);
  58345. }
  58346. this._textures[name] = texture;
  58347. return this;
  58348. };
  58349. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58350. if (this._options.samplers.indexOf(name) === -1) {
  58351. this._options.samplers.push(name);
  58352. }
  58353. this._checkUniform(name);
  58354. this._textureArrays[name] = textures;
  58355. return this;
  58356. };
  58357. ShaderMaterial.prototype.setFloat = function (name, value) {
  58358. this._checkUniform(name);
  58359. this._floats[name] = value;
  58360. return this;
  58361. };
  58362. ShaderMaterial.prototype.setInt = function (name, value) {
  58363. this._checkUniform(name);
  58364. this._ints[name] = value;
  58365. return this;
  58366. };
  58367. ShaderMaterial.prototype.setFloats = function (name, value) {
  58368. this._checkUniform(name);
  58369. this._floatsArrays[name] = value;
  58370. return this;
  58371. };
  58372. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58373. this._checkUniform(name);
  58374. this._colors3[name] = value;
  58375. return this;
  58376. };
  58377. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58378. this._checkUniform(name);
  58379. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58380. color.toArray(arr, arr.length);
  58381. return arr;
  58382. }, []);
  58383. return this;
  58384. };
  58385. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58386. this._checkUniform(name);
  58387. this._colors4[name] = value;
  58388. return this;
  58389. };
  58390. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58391. this._checkUniform(name);
  58392. this._vectors2[name] = value;
  58393. return this;
  58394. };
  58395. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58396. this._checkUniform(name);
  58397. this._vectors3[name] = value;
  58398. return this;
  58399. };
  58400. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58401. this._checkUniform(name);
  58402. this._vectors4[name] = value;
  58403. return this;
  58404. };
  58405. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58406. this._checkUniform(name);
  58407. this._matrices[name] = value;
  58408. return this;
  58409. };
  58410. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58411. this._checkUniform(name);
  58412. this._matrices3x3[name] = value;
  58413. return this;
  58414. };
  58415. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58416. this._checkUniform(name);
  58417. this._matrices2x2[name] = value;
  58418. return this;
  58419. };
  58420. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58421. this._checkUniform(name);
  58422. this._vectors2Arrays[name] = value;
  58423. return this;
  58424. };
  58425. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58426. this._checkUniform(name);
  58427. this._vectors3Arrays[name] = value;
  58428. return this;
  58429. };
  58430. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58431. if (!mesh) {
  58432. return true;
  58433. }
  58434. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58435. return false;
  58436. }
  58437. return false;
  58438. };
  58439. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58440. var scene = this.getScene();
  58441. var engine = scene.getEngine();
  58442. if (!this.checkReadyOnEveryCall) {
  58443. if (this._renderId === scene.getRenderId()) {
  58444. if (this._checkCache(scene, mesh, useInstances)) {
  58445. return true;
  58446. }
  58447. }
  58448. }
  58449. // Instances
  58450. var defines = [];
  58451. var attribs = [];
  58452. var fallbacks = new BABYLON.EffectFallbacks();
  58453. if (useInstances) {
  58454. defines.push("#define INSTANCES");
  58455. }
  58456. for (var index = 0; index < this._options.defines.length; index++) {
  58457. defines.push(this._options.defines[index]);
  58458. }
  58459. for (var index = 0; index < this._options.attributes.length; index++) {
  58460. attribs.push(this._options.attributes[index]);
  58461. }
  58462. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58463. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58464. defines.push("#define VERTEXCOLOR");
  58465. }
  58466. // Bones
  58467. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58468. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58469. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58470. if (mesh.numBoneInfluencers > 4) {
  58471. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58472. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58473. }
  58474. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58475. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58476. fallbacks.addCPUSkinningFallback(0, mesh);
  58477. if (this._options.uniforms.indexOf("mBones") === -1) {
  58478. this._options.uniforms.push("mBones");
  58479. }
  58480. }
  58481. else {
  58482. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58483. }
  58484. // Textures
  58485. for (var name in this._textures) {
  58486. if (!this._textures[name].isReady()) {
  58487. return false;
  58488. }
  58489. }
  58490. // Alpha test
  58491. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58492. defines.push("#define ALPHATEST");
  58493. }
  58494. var previousEffect = this._effect;
  58495. var join = defines.join("\n");
  58496. this._effect = engine.createEffect(this._shaderPath, {
  58497. attributes: attribs,
  58498. uniformsNames: this._options.uniforms,
  58499. uniformBuffersNames: this._options.uniformBuffers,
  58500. samplers: this._options.samplers,
  58501. defines: join,
  58502. fallbacks: fallbacks,
  58503. onCompiled: this.onCompiled,
  58504. onError: this.onError
  58505. }, engine);
  58506. if (!this._effect.isReady()) {
  58507. return false;
  58508. }
  58509. if (previousEffect !== this._effect) {
  58510. scene.resetCachedMaterial();
  58511. }
  58512. this._renderId = scene.getRenderId();
  58513. return true;
  58514. };
  58515. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58516. var scene = this.getScene();
  58517. if (!this._effect) {
  58518. return;
  58519. }
  58520. if (this._options.uniforms.indexOf("world") !== -1) {
  58521. this._effect.setMatrix("world", world);
  58522. }
  58523. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58524. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58525. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58526. }
  58527. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58528. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58529. }
  58530. };
  58531. ShaderMaterial.prototype.bind = function (world, mesh) {
  58532. // Std values
  58533. this.bindOnlyWorldMatrix(world);
  58534. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58535. if (this._options.uniforms.indexOf("view") !== -1) {
  58536. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58537. }
  58538. if (this._options.uniforms.indexOf("projection") !== -1) {
  58539. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58540. }
  58541. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58542. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58543. }
  58544. // Bones
  58545. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58546. var name;
  58547. // Texture
  58548. for (name in this._textures) {
  58549. this._effect.setTexture(name, this._textures[name]);
  58550. }
  58551. // Texture arrays
  58552. for (name in this._textureArrays) {
  58553. this._effect.setTextureArray(name, this._textureArrays[name]);
  58554. }
  58555. // Int
  58556. for (name in this._ints) {
  58557. this._effect.setInt(name, this._ints[name]);
  58558. }
  58559. // Float
  58560. for (name in this._floats) {
  58561. this._effect.setFloat(name, this._floats[name]);
  58562. }
  58563. // Floats
  58564. for (name in this._floatsArrays) {
  58565. this._effect.setArray(name, this._floatsArrays[name]);
  58566. }
  58567. // Color3
  58568. for (name in this._colors3) {
  58569. this._effect.setColor3(name, this._colors3[name]);
  58570. }
  58571. for (name in this._colors3Arrays) {
  58572. this._effect.setArray3(name, this._colors3Arrays[name]);
  58573. }
  58574. // Color4
  58575. for (name in this._colors4) {
  58576. var color = this._colors4[name];
  58577. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58578. }
  58579. // Vector2
  58580. for (name in this._vectors2) {
  58581. this._effect.setVector2(name, this._vectors2[name]);
  58582. }
  58583. // Vector3
  58584. for (name in this._vectors3) {
  58585. this._effect.setVector3(name, this._vectors3[name]);
  58586. }
  58587. // Vector4
  58588. for (name in this._vectors4) {
  58589. this._effect.setVector4(name, this._vectors4[name]);
  58590. }
  58591. // Matrix
  58592. for (name in this._matrices) {
  58593. this._effect.setMatrix(name, this._matrices[name]);
  58594. }
  58595. // Matrix 3x3
  58596. for (name in this._matrices3x3) {
  58597. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58598. }
  58599. // Matrix 2x2
  58600. for (name in this._matrices2x2) {
  58601. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58602. }
  58603. // Vector2Array
  58604. for (name in this._vectors2Arrays) {
  58605. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58606. }
  58607. // Vector3Array
  58608. for (name in this._vectors3Arrays) {
  58609. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58610. }
  58611. }
  58612. this._afterBind(mesh);
  58613. };
  58614. ShaderMaterial.prototype.getActiveTextures = function () {
  58615. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58616. for (var name in this._textures) {
  58617. activeTextures.push(this._textures[name]);
  58618. }
  58619. for (var name in this._textureArrays) {
  58620. var array = this._textureArrays[name];
  58621. for (var index = 0; index < array.length; index++) {
  58622. activeTextures.push(array[index]);
  58623. }
  58624. }
  58625. return activeTextures;
  58626. };
  58627. ShaderMaterial.prototype.hasTexture = function (texture) {
  58628. if (_super.prototype.hasTexture.call(this, texture)) {
  58629. return true;
  58630. }
  58631. for (var name in this._textures) {
  58632. if (this._textures[name] === texture) {
  58633. return true;
  58634. }
  58635. }
  58636. for (var name in this._textureArrays) {
  58637. var array = this._textureArrays[name];
  58638. for (var index = 0; index < array.length; index++) {
  58639. if (array[index] === texture) {
  58640. return true;
  58641. }
  58642. }
  58643. }
  58644. return false;
  58645. };
  58646. ShaderMaterial.prototype.clone = function (name) {
  58647. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58648. return newShaderMaterial;
  58649. };
  58650. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58651. if (forceDisposeTextures) {
  58652. var name;
  58653. for (name in this._textures) {
  58654. this._textures[name].dispose();
  58655. }
  58656. for (name in this._textureArrays) {
  58657. var array = this._textureArrays[name];
  58658. for (var index = 0; index < array.length; index++) {
  58659. array[index].dispose();
  58660. }
  58661. }
  58662. }
  58663. this._textures = {};
  58664. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58665. };
  58666. ShaderMaterial.prototype.serialize = function () {
  58667. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58668. serializationObject.customType = "BABYLON.ShaderMaterial";
  58669. serializationObject.options = this._options;
  58670. serializationObject.shaderPath = this._shaderPath;
  58671. var name;
  58672. // Texture
  58673. serializationObject.textures = {};
  58674. for (name in this._textures) {
  58675. serializationObject.textures[name] = this._textures[name].serialize();
  58676. }
  58677. // Texture arrays
  58678. serializationObject.textureArrays = {};
  58679. for (name in this._textureArrays) {
  58680. serializationObject.textureArrays[name] = [];
  58681. var array = this._textureArrays[name];
  58682. for (var index = 0; index < array.length; index++) {
  58683. serializationObject.textureArrays[name].push(array[index].serialize());
  58684. }
  58685. }
  58686. // Float
  58687. serializationObject.floats = {};
  58688. for (name in this._floats) {
  58689. serializationObject.floats[name] = this._floats[name];
  58690. }
  58691. // Float s
  58692. serializationObject.FloatArrays = {};
  58693. for (name in this._floatsArrays) {
  58694. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58695. }
  58696. // Color3
  58697. serializationObject.colors3 = {};
  58698. for (name in this._colors3) {
  58699. serializationObject.colors3[name] = this._colors3[name].asArray();
  58700. }
  58701. // Color3 array
  58702. serializationObject.colors3Arrays = {};
  58703. for (name in this._colors3Arrays) {
  58704. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58705. }
  58706. // Color4
  58707. serializationObject.colors4 = {};
  58708. for (name in this._colors4) {
  58709. serializationObject.colors4[name] = this._colors4[name].asArray();
  58710. }
  58711. // Vector2
  58712. serializationObject.vectors2 = {};
  58713. for (name in this._vectors2) {
  58714. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58715. }
  58716. // Vector3
  58717. serializationObject.vectors3 = {};
  58718. for (name in this._vectors3) {
  58719. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58720. }
  58721. // Vector4
  58722. serializationObject.vectors4 = {};
  58723. for (name in this._vectors4) {
  58724. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58725. }
  58726. // Matrix
  58727. serializationObject.matrices = {};
  58728. for (name in this._matrices) {
  58729. serializationObject.matrices[name] = this._matrices[name].asArray();
  58730. }
  58731. // Matrix 3x3
  58732. serializationObject.matrices3x3 = {};
  58733. for (name in this._matrices3x3) {
  58734. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58735. }
  58736. // Matrix 2x2
  58737. serializationObject.matrices2x2 = {};
  58738. for (name in this._matrices2x2) {
  58739. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58740. }
  58741. // Vector2Array
  58742. serializationObject.vectors2Arrays = {};
  58743. for (name in this._vectors2Arrays) {
  58744. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58745. }
  58746. // Vector3Array
  58747. serializationObject.vectors3Arrays = {};
  58748. for (name in this._vectors3Arrays) {
  58749. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58750. }
  58751. return serializationObject;
  58752. };
  58753. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58754. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58755. var name;
  58756. // Texture
  58757. for (name in source.textures) {
  58758. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58759. }
  58760. // Texture arrays
  58761. for (name in source.textureArrays) {
  58762. var array = source.textureArrays[name];
  58763. var textureArray = new Array();
  58764. for (var index = 0; index < array.length; index++) {
  58765. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58766. }
  58767. material.setTextureArray(name, textureArray);
  58768. }
  58769. // Float
  58770. for (name in source.floats) {
  58771. material.setFloat(name, source.floats[name]);
  58772. }
  58773. // Float s
  58774. for (name in source.floatsArrays) {
  58775. material.setFloats(name, source.floatsArrays[name]);
  58776. }
  58777. // Color3
  58778. for (name in source.colors3) {
  58779. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58780. }
  58781. // Color3 arrays
  58782. for (name in source.colors3Arrays) {
  58783. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58784. if (i % 3 === 0) {
  58785. arr.push([num]);
  58786. }
  58787. else {
  58788. arr[arr.length - 1].push(num);
  58789. }
  58790. return arr;
  58791. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58792. material.setColor3Array(name, colors);
  58793. }
  58794. // Color4
  58795. for (name in source.colors4) {
  58796. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58797. }
  58798. // Vector2
  58799. for (name in source.vectors2) {
  58800. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58801. }
  58802. // Vector3
  58803. for (name in source.vectors3) {
  58804. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58805. }
  58806. // Vector4
  58807. for (name in source.vectors4) {
  58808. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58809. }
  58810. // Matrix
  58811. for (name in source.matrices) {
  58812. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58813. }
  58814. // Matrix 3x3
  58815. for (name in source.matrices3x3) {
  58816. material.setMatrix3x3(name, source.matrices3x3[name]);
  58817. }
  58818. // Matrix 2x2
  58819. for (name in source.matrices2x2) {
  58820. material.setMatrix2x2(name, source.matrices2x2[name]);
  58821. }
  58822. // Vector2Array
  58823. for (name in source.vectors2Arrays) {
  58824. material.setArray2(name, source.vectors2Arrays[name]);
  58825. }
  58826. // Vector3Array
  58827. for (name in source.vectors3Arrays) {
  58828. material.setArray3(name, source.vectors3Arrays[name]);
  58829. }
  58830. return material;
  58831. };
  58832. return ShaderMaterial;
  58833. }(BABYLON.Material));
  58834. BABYLON.ShaderMaterial = ShaderMaterial;
  58835. })(BABYLON || (BABYLON = {}));
  58836. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58837. "use strict";
  58838. var BABYLON;
  58839. (function (BABYLON) {
  58840. var GroundMesh = /** @class */ (function (_super) {
  58841. __extends(GroundMesh, _super);
  58842. function GroundMesh(name, scene) {
  58843. var _this = _super.call(this, name, scene) || this;
  58844. _this.generateOctree = false;
  58845. return _this;
  58846. }
  58847. GroundMesh.prototype.getClassName = function () {
  58848. return "GroundMesh";
  58849. };
  58850. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58851. get: function () {
  58852. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58853. },
  58854. enumerable: true,
  58855. configurable: true
  58856. });
  58857. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58858. get: function () {
  58859. return this._subdivisionsX;
  58860. },
  58861. enumerable: true,
  58862. configurable: true
  58863. });
  58864. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58865. get: function () {
  58866. return this._subdivisionsY;
  58867. },
  58868. enumerable: true,
  58869. configurable: true
  58870. });
  58871. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58872. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58873. this._subdivisionsX = chunksCount;
  58874. this._subdivisionsY = chunksCount;
  58875. this.subdivide(chunksCount);
  58876. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58877. };
  58878. /**
  58879. * Returns a height (y) value in the Worl system :
  58880. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58881. * Returns the ground y position if (x, z) are outside the ground surface.
  58882. */
  58883. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58884. var world = this.getWorldMatrix();
  58885. var invMat = BABYLON.Tmp.Matrix[5];
  58886. world.invertToRef(invMat);
  58887. var tmpVect = BABYLON.Tmp.Vector3[8];
  58888. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58889. x = tmpVect.x;
  58890. z = tmpVect.z;
  58891. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58892. return this.position.y;
  58893. }
  58894. if (!this._heightQuads || this._heightQuads.length == 0) {
  58895. this._initHeightQuads();
  58896. this._computeHeightQuads();
  58897. }
  58898. var facet = this._getFacetAt(x, z);
  58899. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58900. // return y in the World system
  58901. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58902. return tmpVect.y;
  58903. };
  58904. /**
  58905. * Returns a normalized vector (Vector3) orthogonal to the ground
  58906. * at the ground coordinates (x, z) expressed in the World system.
  58907. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58908. */
  58909. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58910. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58911. this.getNormalAtCoordinatesToRef(x, z, normal);
  58912. return normal;
  58913. };
  58914. /**
  58915. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58916. * at the ground coordinates (x, z) expressed in the World system.
  58917. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58918. * Returns the GroundMesh.
  58919. */
  58920. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58921. var world = this.getWorldMatrix();
  58922. var tmpMat = BABYLON.Tmp.Matrix[5];
  58923. world.invertToRef(tmpMat);
  58924. var tmpVect = BABYLON.Tmp.Vector3[8];
  58925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58926. x = tmpVect.x;
  58927. z = tmpVect.z;
  58928. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58929. return this;
  58930. }
  58931. if (!this._heightQuads || this._heightQuads.length == 0) {
  58932. this._initHeightQuads();
  58933. this._computeHeightQuads();
  58934. }
  58935. var facet = this._getFacetAt(x, z);
  58936. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58937. return this;
  58938. };
  58939. /**
  58940. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58941. * if the ground has been updated.
  58942. * This can be used in the render loop.
  58943. * Returns the GroundMesh.
  58944. */
  58945. GroundMesh.prototype.updateCoordinateHeights = function () {
  58946. if (!this._heightQuads || this._heightQuads.length == 0) {
  58947. this._initHeightQuads();
  58948. }
  58949. this._computeHeightQuads();
  58950. return this;
  58951. };
  58952. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58953. GroundMesh.prototype._getFacetAt = function (x, z) {
  58954. // retrieve col and row from x, z coordinates in the ground local system
  58955. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58956. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58957. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58958. var facet;
  58959. if (z < quad.slope.x * x + quad.slope.y) {
  58960. facet = quad.facet1;
  58961. }
  58962. else {
  58963. facet = quad.facet2;
  58964. }
  58965. return facet;
  58966. };
  58967. // Creates and populates the heightMap array with "facet" elements :
  58968. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58969. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58970. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58971. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58972. // Returns the GroundMesh.
  58973. GroundMesh.prototype._initHeightQuads = function () {
  58974. var subdivisionsX = this._subdivisionsX;
  58975. var subdivisionsY = this._subdivisionsY;
  58976. this._heightQuads = new Array();
  58977. for (var row = 0; row < subdivisionsY; row++) {
  58978. for (var col = 0; col < subdivisionsX; col++) {
  58979. 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) };
  58980. this._heightQuads[row * subdivisionsX + col] = quad;
  58981. }
  58982. }
  58983. return this;
  58984. };
  58985. // Compute each quad element values and update the the heightMap array :
  58986. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58987. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58988. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58989. // Returns the GroundMesh.
  58990. GroundMesh.prototype._computeHeightQuads = function () {
  58991. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58992. if (!positions) {
  58993. return this;
  58994. }
  58995. var v1 = BABYLON.Tmp.Vector3[3];
  58996. var v2 = BABYLON.Tmp.Vector3[2];
  58997. var v3 = BABYLON.Tmp.Vector3[1];
  58998. var v4 = BABYLON.Tmp.Vector3[0];
  58999. var v1v2 = BABYLON.Tmp.Vector3[4];
  59000. var v1v3 = BABYLON.Tmp.Vector3[5];
  59001. var v1v4 = BABYLON.Tmp.Vector3[6];
  59002. var norm1 = BABYLON.Tmp.Vector3[7];
  59003. var norm2 = BABYLON.Tmp.Vector3[8];
  59004. var i = 0;
  59005. var j = 0;
  59006. var k = 0;
  59007. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59008. var h = 0;
  59009. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59010. var d2 = 0;
  59011. var subdivisionsX = this._subdivisionsX;
  59012. var subdivisionsY = this._subdivisionsY;
  59013. for (var row = 0; row < subdivisionsY; row++) {
  59014. for (var col = 0; col < subdivisionsX; col++) {
  59015. i = col * 3;
  59016. j = row * (subdivisionsX + 1) * 3;
  59017. k = (row + 1) * (subdivisionsX + 1) * 3;
  59018. v1.x = positions[j + i];
  59019. v1.y = positions[j + i + 1];
  59020. v1.z = positions[j + i + 2];
  59021. v2.x = positions[j + i + 3];
  59022. v2.y = positions[j + i + 4];
  59023. v2.z = positions[j + i + 5];
  59024. v3.x = positions[k + i];
  59025. v3.y = positions[k + i + 1];
  59026. v3.z = positions[k + i + 2];
  59027. v4.x = positions[k + i + 3];
  59028. v4.y = positions[k + i + 4];
  59029. v4.z = positions[k + i + 5];
  59030. // 2D slope V1V4
  59031. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59032. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59033. // facet equations :
  59034. // we compute each facet normal vector
  59035. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59036. // we compute the value d by applying the equation to v1 which belongs to the plane
  59037. // then we store the facet equation in a Vector4
  59038. v2.subtractToRef(v1, v1v2);
  59039. v3.subtractToRef(v1, v1v3);
  59040. v4.subtractToRef(v1, v1v4);
  59041. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59042. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59043. norm1.normalize();
  59044. norm2.normalize();
  59045. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59046. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59047. var quad = this._heightQuads[row * subdivisionsX + col];
  59048. quad.slope.copyFromFloats(cd, h);
  59049. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59050. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59051. }
  59052. }
  59053. return this;
  59054. };
  59055. GroundMesh.prototype.serialize = function (serializationObject) {
  59056. _super.prototype.serialize.call(this, serializationObject);
  59057. serializationObject.subdivisionsX = this._subdivisionsX;
  59058. serializationObject.subdivisionsY = this._subdivisionsY;
  59059. serializationObject.minX = this._minX;
  59060. serializationObject.maxX = this._maxX;
  59061. serializationObject.minZ = this._minZ;
  59062. serializationObject.maxZ = this._maxZ;
  59063. serializationObject.width = this._width;
  59064. serializationObject.height = this._height;
  59065. };
  59066. GroundMesh.Parse = function (parsedMesh, scene) {
  59067. var result = new GroundMesh(parsedMesh.name, scene);
  59068. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59069. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59070. result._minX = parsedMesh.minX;
  59071. result._maxX = parsedMesh.maxX;
  59072. result._minZ = parsedMesh.minZ;
  59073. result._maxZ = parsedMesh.maxZ;
  59074. result._width = parsedMesh.width;
  59075. result._height = parsedMesh.height;
  59076. return result;
  59077. };
  59078. return GroundMesh;
  59079. }(BABYLON.Mesh));
  59080. BABYLON.GroundMesh = GroundMesh;
  59081. })(BABYLON || (BABYLON = {}));
  59082. //# sourceMappingURL=babylon.groundMesh.js.map
  59083. "use strict";
  59084. var BABYLON;
  59085. (function (BABYLON) {
  59086. /**
  59087. * Creates an instance based on a source mesh.
  59088. */
  59089. var InstancedMesh = /** @class */ (function (_super) {
  59090. __extends(InstancedMesh, _super);
  59091. function InstancedMesh(name, source) {
  59092. var _this = _super.call(this, name, source.getScene()) || this;
  59093. source.instances.push(_this);
  59094. _this._sourceMesh = source;
  59095. _this.position.copyFrom(source.position);
  59096. _this.rotation.copyFrom(source.rotation);
  59097. _this.scaling.copyFrom(source.scaling);
  59098. if (source.rotationQuaternion) {
  59099. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59100. }
  59101. _this.infiniteDistance = source.infiniteDistance;
  59102. _this.setPivotMatrix(source.getPivotMatrix());
  59103. _this.refreshBoundingInfo();
  59104. _this._syncSubMeshes();
  59105. return _this;
  59106. }
  59107. /**
  59108. * Returns the string "InstancedMesh".
  59109. */
  59110. InstancedMesh.prototype.getClassName = function () {
  59111. return "InstancedMesh";
  59112. };
  59113. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59114. // Methods
  59115. get: function () {
  59116. return this._sourceMesh.receiveShadows;
  59117. },
  59118. enumerable: true,
  59119. configurable: true
  59120. });
  59121. Object.defineProperty(InstancedMesh.prototype, "material", {
  59122. get: function () {
  59123. return this._sourceMesh.material;
  59124. },
  59125. enumerable: true,
  59126. configurable: true
  59127. });
  59128. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59129. get: function () {
  59130. return this._sourceMesh.visibility;
  59131. },
  59132. enumerable: true,
  59133. configurable: true
  59134. });
  59135. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59136. get: function () {
  59137. return this._sourceMesh.skeleton;
  59138. },
  59139. enumerable: true,
  59140. configurable: true
  59141. });
  59142. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59143. get: function () {
  59144. return this._sourceMesh.renderingGroupId;
  59145. },
  59146. set: function (value) {
  59147. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59148. return;
  59149. }
  59150. //no-op with warning
  59151. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59152. },
  59153. enumerable: true,
  59154. configurable: true
  59155. });
  59156. /**
  59157. * Returns the total number of vertices (integer).
  59158. */
  59159. InstancedMesh.prototype.getTotalVertices = function () {
  59160. return this._sourceMesh.getTotalVertices();
  59161. };
  59162. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59163. get: function () {
  59164. return this._sourceMesh;
  59165. },
  59166. enumerable: true,
  59167. configurable: true
  59168. });
  59169. /**
  59170. * Is this node ready to be used/rendered
  59171. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59172. * @return {boolean} is it ready
  59173. */
  59174. InstancedMesh.prototype.isReady = function (completeCheck) {
  59175. if (completeCheck === void 0) { completeCheck = false; }
  59176. return this._sourceMesh.isReady(completeCheck, true);
  59177. };
  59178. /**
  59179. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59180. */
  59181. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59182. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59183. };
  59184. /**
  59185. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59186. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59187. * The `data` are either a numeric array either a Float32Array.
  59188. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59189. * 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).
  59190. * Note that a new underlying VertexBuffer object is created each call.
  59191. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59192. *
  59193. * Possible `kind` values :
  59194. * - BABYLON.VertexBuffer.PositionKind
  59195. * - BABYLON.VertexBuffer.UVKind
  59196. * - BABYLON.VertexBuffer.UV2Kind
  59197. * - BABYLON.VertexBuffer.UV3Kind
  59198. * - BABYLON.VertexBuffer.UV4Kind
  59199. * - BABYLON.VertexBuffer.UV5Kind
  59200. * - BABYLON.VertexBuffer.UV6Kind
  59201. * - BABYLON.VertexBuffer.ColorKind
  59202. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59203. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59204. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59205. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59206. *
  59207. * Returns the Mesh.
  59208. */
  59209. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59210. if (this.sourceMesh) {
  59211. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59212. }
  59213. return this.sourceMesh;
  59214. };
  59215. /**
  59216. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59217. * If the mesh has no geometry, it is simply returned as it is.
  59218. * The `data` are either a numeric array either a Float32Array.
  59219. * No new underlying VertexBuffer object is created.
  59220. * 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.
  59221. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59222. *
  59223. * Possible `kind` values :
  59224. * - BABYLON.VertexBuffer.PositionKind
  59225. * - BABYLON.VertexBuffer.UVKind
  59226. * - BABYLON.VertexBuffer.UV2Kind
  59227. * - BABYLON.VertexBuffer.UV3Kind
  59228. * - BABYLON.VertexBuffer.UV4Kind
  59229. * - BABYLON.VertexBuffer.UV5Kind
  59230. * - BABYLON.VertexBuffer.UV6Kind
  59231. * - BABYLON.VertexBuffer.ColorKind
  59232. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59233. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59234. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59235. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59236. *
  59237. * Returns the Mesh.
  59238. */
  59239. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59240. if (this.sourceMesh) {
  59241. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59242. }
  59243. return this.sourceMesh;
  59244. };
  59245. /**
  59246. * Sets the mesh indices.
  59247. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59248. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59249. * This method creates a new index buffer each call.
  59250. * Returns the Mesh.
  59251. */
  59252. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59253. if (totalVertices === void 0) { totalVertices = null; }
  59254. if (this.sourceMesh) {
  59255. this.sourceMesh.setIndices(indices, totalVertices);
  59256. }
  59257. return this.sourceMesh;
  59258. };
  59259. /**
  59260. * Boolean : True if the mesh owns the requested kind of data.
  59261. */
  59262. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59263. return this._sourceMesh.isVerticesDataPresent(kind);
  59264. };
  59265. /**
  59266. * Returns an array of indices (IndicesArray).
  59267. */
  59268. InstancedMesh.prototype.getIndices = function () {
  59269. return this._sourceMesh.getIndices();
  59270. };
  59271. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59272. get: function () {
  59273. return this._sourceMesh._positions;
  59274. },
  59275. enumerable: true,
  59276. configurable: true
  59277. });
  59278. /**
  59279. * Sets a new updated BoundingInfo to the mesh.
  59280. * Returns the mesh.
  59281. */
  59282. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59283. var meshBB = this._sourceMesh.getBoundingInfo();
  59284. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59285. this._updateBoundingInfo();
  59286. return this;
  59287. };
  59288. InstancedMesh.prototype._preActivate = function () {
  59289. if (this._currentLOD) {
  59290. this._currentLOD._preActivate();
  59291. }
  59292. return this;
  59293. };
  59294. InstancedMesh.prototype._activate = function (renderId) {
  59295. if (this._currentLOD) {
  59296. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59297. }
  59298. return this;
  59299. };
  59300. /**
  59301. * Returns the current associated LOD AbstractMesh.
  59302. */
  59303. InstancedMesh.prototype.getLOD = function (camera) {
  59304. if (!camera) {
  59305. return this;
  59306. }
  59307. var boundingInfo = this.getBoundingInfo();
  59308. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59309. if (this._currentLOD === this.sourceMesh) {
  59310. return this;
  59311. }
  59312. return this._currentLOD;
  59313. };
  59314. InstancedMesh.prototype._syncSubMeshes = function () {
  59315. this.releaseSubMeshes();
  59316. if (this._sourceMesh.subMeshes) {
  59317. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59318. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59319. }
  59320. }
  59321. return this;
  59322. };
  59323. InstancedMesh.prototype._generatePointsArray = function () {
  59324. return this._sourceMesh._generatePointsArray();
  59325. };
  59326. /**
  59327. * Creates a new InstancedMesh from the current mesh.
  59328. * - name (string) : the cloned mesh name
  59329. * - newParent (optional Node) : the optional Node to parent the clone to.
  59330. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59331. *
  59332. * Returns the clone.
  59333. */
  59334. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59335. var result = this._sourceMesh.createInstance(name);
  59336. // Deep copy
  59337. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59338. // Bounding info
  59339. this.refreshBoundingInfo();
  59340. // Parent
  59341. if (newParent) {
  59342. result.parent = newParent;
  59343. }
  59344. if (!doNotCloneChildren) {
  59345. // Children
  59346. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59347. var mesh = this.getScene().meshes[index];
  59348. if (mesh.parent === this) {
  59349. mesh.clone(mesh.name, result);
  59350. }
  59351. }
  59352. }
  59353. result.computeWorldMatrix(true);
  59354. return result;
  59355. };
  59356. /**
  59357. * Disposes the InstancedMesh.
  59358. * Returns nothing.
  59359. */
  59360. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59361. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59362. // Remove from mesh
  59363. var index = this._sourceMesh.instances.indexOf(this);
  59364. this._sourceMesh.instances.splice(index, 1);
  59365. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59366. };
  59367. return InstancedMesh;
  59368. }(BABYLON.AbstractMesh));
  59369. BABYLON.InstancedMesh = InstancedMesh;
  59370. })(BABYLON || (BABYLON = {}));
  59371. //# sourceMappingURL=babylon.instancedMesh.js.map
  59372. "use strict";
  59373. var BABYLON;
  59374. (function (BABYLON) {
  59375. var LinesMesh = /** @class */ (function (_super) {
  59376. __extends(LinesMesh, _super);
  59377. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59378. if (scene === void 0) { scene = null; }
  59379. if (parent === void 0) { parent = null; }
  59380. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59381. _this.useVertexColor = useVertexColor;
  59382. _this.useVertexAlpha = useVertexAlpha;
  59383. _this.color = new BABYLON.Color3(1, 1, 1);
  59384. _this.alpha = 1;
  59385. if (source) {
  59386. _this.color = source.color.clone();
  59387. _this.alpha = source.alpha;
  59388. _this.useVertexColor = source.useVertexColor;
  59389. _this.useVertexAlpha = source.useVertexAlpha;
  59390. }
  59391. _this._intersectionThreshold = 0.1;
  59392. var defines = [];
  59393. var options = {
  59394. attributes: [BABYLON.VertexBuffer.PositionKind],
  59395. uniforms: ["world", "viewProjection"],
  59396. needAlphaBlending: true,
  59397. defines: defines
  59398. };
  59399. if (useVertexAlpha === false) {
  59400. options.needAlphaBlending = false;
  59401. }
  59402. if (!useVertexColor) {
  59403. options.uniforms.push("color");
  59404. }
  59405. else {
  59406. options.defines.push("#define VERTEXCOLOR");
  59407. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59408. }
  59409. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59410. return _this;
  59411. }
  59412. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59413. /**
  59414. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59415. * This margin is expressed in world space coordinates, so its value may vary.
  59416. * Default value is 0.1
  59417. * @returns the intersection Threshold value.
  59418. */
  59419. get: function () {
  59420. return this._intersectionThreshold;
  59421. },
  59422. /**
  59423. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59424. * This margin is expressed in world space coordinates, so its value may vary.
  59425. * @param value the new threshold to apply
  59426. */
  59427. set: function (value) {
  59428. if (this._intersectionThreshold === value) {
  59429. return;
  59430. }
  59431. this._intersectionThreshold = value;
  59432. if (this.geometry) {
  59433. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59434. }
  59435. },
  59436. enumerable: true,
  59437. configurable: true
  59438. });
  59439. /**
  59440. * Returns the string "LineMesh"
  59441. */
  59442. LinesMesh.prototype.getClassName = function () {
  59443. return "LinesMesh";
  59444. };
  59445. Object.defineProperty(LinesMesh.prototype, "material", {
  59446. get: function () {
  59447. return this._colorShader;
  59448. },
  59449. set: function (value) {
  59450. // Do nothing
  59451. },
  59452. enumerable: true,
  59453. configurable: true
  59454. });
  59455. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59456. get: function () {
  59457. return false;
  59458. },
  59459. enumerable: true,
  59460. configurable: true
  59461. });
  59462. LinesMesh.prototype.createInstance = function (name) {
  59463. throw new Error("LinesMeshes do not support createInstance.");
  59464. };
  59465. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59466. if (!this._geometry) {
  59467. return this;
  59468. }
  59469. // VBOs
  59470. this._geometry._bind(this._colorShader.getEffect());
  59471. // Color
  59472. if (!this.useVertexColor) {
  59473. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59474. }
  59475. return this;
  59476. };
  59477. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59478. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59479. return this;
  59480. }
  59481. var engine = this.getScene().getEngine();
  59482. // Draw order
  59483. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59484. return this;
  59485. };
  59486. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59487. this._colorShader.dispose();
  59488. _super.prototype.dispose.call(this, doNotRecurse);
  59489. };
  59490. /**
  59491. * Returns a new LineMesh object cloned from the current one.
  59492. */
  59493. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59494. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59495. };
  59496. return LinesMesh;
  59497. }(BABYLON.Mesh));
  59498. BABYLON.LinesMesh = LinesMesh;
  59499. })(BABYLON || (BABYLON = {}));
  59500. //# sourceMappingURL=babylon.linesMesh.js.map
  59501. "use strict";
  59502. var BABYLON;
  59503. (function (BABYLON) {
  59504. /**
  59505. * Class containing static functions to help procedurally build meshes
  59506. */
  59507. var MeshBuilder = /** @class */ (function () {
  59508. function MeshBuilder() {
  59509. }
  59510. MeshBuilder.updateSideOrientation = function (orientation) {
  59511. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59512. return BABYLON.Mesh.DOUBLESIDE;
  59513. }
  59514. if (orientation === undefined || orientation === null) {
  59515. return BABYLON.Mesh.FRONTSIDE;
  59516. }
  59517. return orientation;
  59518. };
  59519. /**
  59520. * Creates a box mesh
  59521. * * The parameter `size` sets the size (float) of each box side (default 1)
  59522. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59523. * * 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)
  59524. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59525. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59526. * * 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
  59527. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59528. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59529. * @param name defines the name of the mesh
  59530. * @param options defines the options used to create the mesh
  59531. * @param scene defines the hosting scene
  59532. * @returns the box mesh
  59533. */
  59534. MeshBuilder.CreateBox = function (name, options, scene) {
  59535. if (scene === void 0) { scene = null; }
  59536. var box = new BABYLON.Mesh(name, scene);
  59537. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59538. box._originalBuilderSideOrientation = options.sideOrientation;
  59539. var vertexData = BABYLON.VertexData.CreateBox(options);
  59540. vertexData.applyToMesh(box, options.updatable);
  59541. return box;
  59542. };
  59543. /**
  59544. * Creates a sphere mesh
  59545. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59546. * * 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`)
  59547. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59548. * * 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
  59549. * * 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)
  59550. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59551. * * 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
  59552. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59553. * @param name defines the name of the mesh
  59554. * @param options defines the options used to create the mesh
  59555. * @param scene defines the hosting scene
  59556. * @returns the sphere mesh
  59557. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59558. */
  59559. MeshBuilder.CreateSphere = function (name, options, scene) {
  59560. var sphere = new BABYLON.Mesh(name, scene);
  59561. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59562. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59563. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59564. vertexData.applyToMesh(sphere, options.updatable);
  59565. return sphere;
  59566. };
  59567. /**
  59568. * Creates a plane polygonal mesh. By default, this is a disc
  59569. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59570. * * 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
  59571. * * 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
  59572. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59573. * * 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
  59574. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59575. * @param name defines the name of the mesh
  59576. * @param options defines the options used to create the mesh
  59577. * @param scene defines the hosting scene
  59578. * @returns the plane polygonal mesh
  59579. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  59580. */
  59581. MeshBuilder.CreateDisc = function (name, options, scene) {
  59582. if (scene === void 0) { scene = null; }
  59583. var disc = new BABYLON.Mesh(name, scene);
  59584. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59585. disc._originalBuilderSideOrientation = options.sideOrientation;
  59586. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59587. vertexData.applyToMesh(disc, options.updatable);
  59588. return disc;
  59589. };
  59590. /**
  59591. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59592. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59593. * * 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`)
  59594. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59595. * * 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
  59596. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59597. * * 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
  59598. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59599. * @param name defines the name of the mesh
  59600. * @param options defines the options used to create the mesh
  59601. * @param scene defines the hosting scene
  59602. * @returns the icosahedron mesh
  59603. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  59604. */
  59605. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59606. var sphere = new BABYLON.Mesh(name, scene);
  59607. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59608. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59609. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59610. vertexData.applyToMesh(sphere, options.updatable);
  59611. return sphere;
  59612. };
  59613. ;
  59614. /**
  59615. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59616. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59617. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59618. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59619. * * 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
  59620. * * 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
  59621. * * 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
  59622. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59623. * * 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
  59624. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59625. * * 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
  59626. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59627. * * 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
  59628. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59629. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59630. * @param name defines the name of the mesh
  59631. * @param options defines the options used to create the mesh
  59632. * @param scene defines the hosting scene
  59633. * @returns the ribbon mesh
  59634. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59635. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59636. */
  59637. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59638. if (scene === void 0) { scene = null; }
  59639. var pathArray = options.pathArray;
  59640. var closeArray = options.closeArray;
  59641. var closePath = options.closePath;
  59642. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59643. var instance = options.instance;
  59644. var updatable = options.updatable;
  59645. if (instance) {
  59646. // positionFunction : ribbon case
  59647. // only pathArray and sideOrientation parameters are taken into account for positions update
  59648. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59649. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59650. var positionFunction = function (positions) {
  59651. var minlg = pathArray[0].length;
  59652. var i = 0;
  59653. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59654. for (var si = 1; si <= ns; si++) {
  59655. for (var p = 0; p < pathArray.length; p++) {
  59656. var path = pathArray[p];
  59657. var l = path.length;
  59658. minlg = (minlg < l) ? minlg : l;
  59659. var j = 0;
  59660. while (j < minlg) {
  59661. positions[i] = path[j].x;
  59662. positions[i + 1] = path[j].y;
  59663. positions[i + 2] = path[j].z;
  59664. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59665. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59666. }
  59667. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59668. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59669. }
  59670. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59671. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59672. }
  59673. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59674. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59675. }
  59676. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59677. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59678. }
  59679. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59680. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59681. }
  59682. j++;
  59683. i += 3;
  59684. }
  59685. if (instance._closePath) {
  59686. positions[i] = path[0].x;
  59687. positions[i + 1] = path[0].y;
  59688. positions[i + 2] = path[0].z;
  59689. i += 3;
  59690. }
  59691. }
  59692. }
  59693. };
  59694. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59695. positionFunction(positions);
  59696. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59697. instance._boundingInfo.update(instance._worldMatrix);
  59698. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59699. if (options.colors) {
  59700. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59701. for (var c = 0; c < options.colors.length; c++) {
  59702. colors[c * 4] = options.colors[c].r;
  59703. colors[c * 4 + 1] = options.colors[c].g;
  59704. colors[c * 4 + 2] = options.colors[c].b;
  59705. colors[c * 4 + 3] = options.colors[c].a;
  59706. }
  59707. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59708. }
  59709. if (options.uvs) {
  59710. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59711. for (var i = 0; i < options.uvs.length; i++) {
  59712. uvs[i * 2] = options.uvs[i].x;
  59713. uvs[i * 2 + 1] = options.uvs[i].y;
  59714. }
  59715. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59716. }
  59717. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59718. var indices = instance.getIndices();
  59719. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59720. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59721. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59722. if (instance._closePath) {
  59723. var indexFirst = 0;
  59724. var indexLast = 0;
  59725. for (var p = 0; p < pathArray.length; p++) {
  59726. indexFirst = instance._idx[p] * 3;
  59727. if (p + 1 < pathArray.length) {
  59728. indexLast = (instance._idx[p + 1] - 1) * 3;
  59729. }
  59730. else {
  59731. indexLast = normals.length - 3;
  59732. }
  59733. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59734. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59735. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59736. normals[indexLast] = normals[indexFirst];
  59737. normals[indexLast + 1] = normals[indexFirst + 1];
  59738. normals[indexLast + 2] = normals[indexFirst + 2];
  59739. }
  59740. }
  59741. if (!(instance.areNormalsFrozen)) {
  59742. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59743. }
  59744. }
  59745. return instance;
  59746. }
  59747. else {
  59748. var ribbon = new BABYLON.Mesh(name, scene);
  59749. ribbon._originalBuilderSideOrientation = sideOrientation;
  59750. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59751. if (closePath) {
  59752. ribbon._idx = vertexData._idx;
  59753. }
  59754. ribbon._closePath = closePath;
  59755. ribbon._closeArray = closeArray;
  59756. vertexData.applyToMesh(ribbon, updatable);
  59757. return ribbon;
  59758. }
  59759. };
  59760. /**
  59761. * Creates a cylinder or a cone mesh
  59762. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59763. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59764. * * 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.
  59765. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59766. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59767. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59768. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59769. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59770. * * 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).
  59771. * * 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
  59772. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59773. * * 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
  59774. * * 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.
  59775. * * If `enclose` is false, a ring surface is one element.
  59776. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59777. * * 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
  59778. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59779. * * 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
  59780. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59781. * @param name defines the name of the mesh
  59782. * @param options defines the options used to create the mesh
  59783. * @param scene defines the hosting scene
  59784. * @returns the cylinder mesh
  59785. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59786. */
  59787. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59788. var cylinder = new BABYLON.Mesh(name, scene);
  59789. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59790. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59791. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59792. vertexData.applyToMesh(cylinder, options.updatable);
  59793. return cylinder;
  59794. };
  59795. /**
  59796. * Creates a torus mesh
  59797. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59798. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59799. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59800. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59801. * * 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
  59802. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59803. * @param name defines the name of the mesh
  59804. * @param options defines the options used to create the mesh
  59805. * @param scene defines the hosting scene
  59806. * @returns the torus mesh
  59807. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  59808. */
  59809. MeshBuilder.CreateTorus = function (name, options, scene) {
  59810. var torus = new BABYLON.Mesh(name, scene);
  59811. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59812. torus._originalBuilderSideOrientation = options.sideOrientation;
  59813. var vertexData = BABYLON.VertexData.CreateTorus(options);
  59814. vertexData.applyToMesh(torus, options.updatable);
  59815. return torus;
  59816. };
  59817. /**
  59818. * Creates a torus knot mesh
  59819. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  59820. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  59821. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  59822. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  59823. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59824. * * 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
  59825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59826. * @param name defines the name of the mesh
  59827. * @param options defines the options used to create the mesh
  59828. * @param scene defines the hosting scene
  59829. * @returns the torus knot mesh
  59830. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  59831. */
  59832. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  59833. var torusKnot = new BABYLON.Mesh(name, scene);
  59834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59835. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  59836. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  59837. vertexData.applyToMesh(torusKnot, options.updatable);
  59838. return torusKnot;
  59839. };
  59840. /**
  59841. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  59842. * * 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
  59843. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  59844. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  59845. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  59846. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  59847. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  59848. * * 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
  59849. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  59850. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59851. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  59852. * @param name defines the name of the new line system
  59853. * @param options defines the options used to create the line system
  59854. * @param scene defines the hosting scene
  59855. * @returns a new line system mesh
  59856. */
  59857. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  59858. var instance = options.instance;
  59859. var lines = options.lines;
  59860. var colors = options.colors;
  59861. if (instance) {
  59862. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59863. var vertexColor;
  59864. var lineColors;
  59865. if (colors) {
  59866. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59867. }
  59868. var i = 0;
  59869. var c = 0;
  59870. for (var l = 0; l < lines.length; l++) {
  59871. var points = lines[l];
  59872. for (var p = 0; p < points.length; p++) {
  59873. positions[i] = points[p].x;
  59874. positions[i + 1] = points[p].y;
  59875. positions[i + 2] = points[p].z;
  59876. if (colors && vertexColor) {
  59877. lineColors = colors[l];
  59878. vertexColor[c] = lineColors[p].r;
  59879. vertexColor[c + 1] = lineColors[p].g;
  59880. vertexColor[c + 2] = lineColors[p].b;
  59881. vertexColor[c + 3] = lineColors[p].a;
  59882. c += 4;
  59883. }
  59884. i += 3;
  59885. }
  59886. }
  59887. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59888. if (colors && vertexColor) {
  59889. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  59890. }
  59891. return instance;
  59892. }
  59893. // line system creation
  59894. var useVertexColor = (colors) ? true : false;
  59895. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  59896. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  59897. vertexData.applyToMesh(lineSystem, options.updatable);
  59898. return lineSystem;
  59899. };
  59900. /**
  59901. * Creates a line mesh
  59902. * 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
  59903. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59904. * * The parameter `points` is an array successive Vector3
  59905. * * 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
  59906. * * The optional parameter `colors` is an array of successive Color4, one per line point
  59907. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  59908. * * When updating an instance, remember that only point positions can change, not the number of points
  59909. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59910. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  59911. * @param name defines the name of the new line system
  59912. * @param options defines the options used to create the line system
  59913. * @param scene defines the hosting scene
  59914. * @returns a new line mesh
  59915. */
  59916. MeshBuilder.CreateLines = function (name, options, scene) {
  59917. if (scene === void 0) { scene = null; }
  59918. var colors = (options.colors) ? [options.colors] : null;
  59919. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59920. return lines;
  59921. };
  59922. /**
  59923. * Creates a dashed line mesh
  59924. * * 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
  59925. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59926. * * The parameter `points` is an array successive Vector3
  59927. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  59928. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  59929. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  59930. * * 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
  59931. * * When updating an instance, remember that only point positions can change, not the number of points
  59932. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59933. * @param name defines the name of the mesh
  59934. * @param options defines the options used to create the mesh
  59935. * @param scene defines the hosting scene
  59936. * @returns the dashed line mesh
  59937. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59938. */
  59939. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59940. if (scene === void 0) { scene = null; }
  59941. var points = options.points;
  59942. var instance = options.instance;
  59943. var gapSize = options.gapSize || 1;
  59944. var dashSize = options.dashSize || 3;
  59945. if (instance) {
  59946. var positionFunction = function (positions) {
  59947. var curvect = BABYLON.Vector3.Zero();
  59948. var nbSeg = positions.length / 6;
  59949. var lg = 0;
  59950. var nb = 0;
  59951. var shft = 0;
  59952. var dashshft = 0;
  59953. var curshft = 0;
  59954. var p = 0;
  59955. var i = 0;
  59956. var j = 0;
  59957. for (i = 0; i < points.length - 1; i++) {
  59958. points[i + 1].subtractToRef(points[i], curvect);
  59959. lg += curvect.length();
  59960. }
  59961. shft = lg / nbSeg;
  59962. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59963. for (i = 0; i < points.length - 1; i++) {
  59964. points[i + 1].subtractToRef(points[i], curvect);
  59965. nb = Math.floor(curvect.length() / shft);
  59966. curvect.normalize();
  59967. j = 0;
  59968. while (j < nb && p < positions.length) {
  59969. curshft = shft * j;
  59970. positions[p] = points[i].x + curshft * curvect.x;
  59971. positions[p + 1] = points[i].y + curshft * curvect.y;
  59972. positions[p + 2] = points[i].z + curshft * curvect.z;
  59973. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59974. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59975. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59976. p += 6;
  59977. j++;
  59978. }
  59979. }
  59980. while (p < positions.length) {
  59981. positions[p] = points[i].x;
  59982. positions[p + 1] = points[i].y;
  59983. positions[p + 2] = points[i].z;
  59984. p += 3;
  59985. }
  59986. };
  59987. instance.updateMeshPositions(positionFunction, false);
  59988. return instance;
  59989. }
  59990. // dashed lines creation
  59991. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59992. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59993. vertexData.applyToMesh(dashedLines, options.updatable);
  59994. dashedLines.dashSize = dashSize;
  59995. dashedLines.gapSize = gapSize;
  59996. return dashedLines;
  59997. };
  59998. /**
  59999. * 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.
  60000. * * 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.
  60001. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60002. * * 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.
  60003. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60004. * * 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
  60005. * * 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
  60006. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60007. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60008. * * 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
  60009. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60010. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60011. * @param name defines the name of the mesh
  60012. * @param options defines the options used to create the mesh
  60013. * @param scene defines the hosting scene
  60014. * @returns the extruded shape mesh
  60015. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60016. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60017. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60018. */
  60019. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60020. if (scene === void 0) { scene = null; }
  60021. var path = options.path;
  60022. var shape = options.shape;
  60023. var scale = options.scale || 1;
  60024. var rotation = options.rotation || 0;
  60025. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60026. var updatable = options.updatable;
  60027. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60028. var instance = options.instance || null;
  60029. var invertUV = options.invertUV || false;
  60030. 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);
  60031. };
  60032. /**
  60033. * Creates an custom extruded shape mesh.
  60034. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60035. * * 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.
  60036. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60037. * * 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
  60038. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60039. * * 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
  60040. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60041. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60042. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60043. * * 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
  60044. * * 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
  60045. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60046. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60047. * * 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
  60048. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60049. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60050. * @param name defines the name of the mesh
  60051. * @param options defines the options used to create the mesh
  60052. * @param scene defines the hosting scene
  60053. * @returns the custom extruded shape mesh
  60054. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60055. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60056. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60057. */
  60058. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60059. var path = options.path;
  60060. var shape = options.shape;
  60061. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60062. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60063. var ribbonCloseArray = options.ribbonCloseArray || false;
  60064. var ribbonClosePath = options.ribbonClosePath || false;
  60065. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60066. var updatable = options.updatable;
  60067. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60068. var instance = options.instance;
  60069. var invertUV = options.invertUV || false;
  60070. 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);
  60071. };
  60072. /**
  60073. * Creates lathe mesh.
  60074. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60075. * * 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
  60076. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60077. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60078. * * 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
  60079. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60080. * * 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
  60081. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60082. * * 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
  60083. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60084. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60085. * @param name defines the name of the mesh
  60086. * @param options defines the options used to create the mesh
  60087. * @param scene defines the hosting scene
  60088. * @returns the lathe mesh
  60089. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60090. */
  60091. MeshBuilder.CreateLathe = function (name, options, scene) {
  60092. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60093. var closed = (options.closed === undefined) ? true : options.closed;
  60094. var shape = options.shape;
  60095. var radius = options.radius || 1;
  60096. var tessellation = options.tessellation || 64;
  60097. var updatable = options.updatable;
  60098. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60099. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60100. var pi2 = Math.PI * 2;
  60101. var paths = new Array();
  60102. var invertUV = options.invertUV || false;
  60103. var i = 0;
  60104. var p = 0;
  60105. var step = pi2 / tessellation * arc;
  60106. var rotated;
  60107. var path = new Array();
  60108. ;
  60109. for (i = 0; i <= tessellation; i++) {
  60110. var path = [];
  60111. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60112. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60113. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60114. }
  60115. for (p = 0; p < shape.length; p++) {
  60116. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60117. path.push(rotated);
  60118. }
  60119. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60120. 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));
  60121. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60122. }
  60123. paths.push(path);
  60124. }
  60125. // lathe ribbon
  60126. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60127. return lathe;
  60128. };
  60129. /**
  60130. * Creates a plane mesh
  60131. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60132. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60133. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60134. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60135. * * 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
  60136. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60137. * @param name defines the name of the mesh
  60138. * @param options defines the options used to create the mesh
  60139. * @param scene defines the hosting scene
  60140. * @returns the plane mesh
  60141. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60142. */
  60143. MeshBuilder.CreatePlane = function (name, options, scene) {
  60144. var plane = new BABYLON.Mesh(name, scene);
  60145. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60146. plane._originalBuilderSideOrientation = options.sideOrientation;
  60147. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60148. vertexData.applyToMesh(plane, options.updatable);
  60149. if (options.sourcePlane) {
  60150. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60151. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60152. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60153. plane.rotate(vectorProduct, product);
  60154. }
  60155. return plane;
  60156. };
  60157. /**
  60158. * Creates a ground mesh
  60159. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60160. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60161. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60162. * @param name defines the name of the mesh
  60163. * @param options defines the options used to create the mesh
  60164. * @param scene defines the hosting scene
  60165. * @returns the ground mesh
  60166. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60167. */
  60168. MeshBuilder.CreateGround = function (name, options, scene) {
  60169. var ground = new BABYLON.GroundMesh(name, scene);
  60170. ground._setReady(false);
  60171. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60172. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60173. ground._width = options.width || 1;
  60174. ground._height = options.height || 1;
  60175. ground._maxX = ground._width / 2;
  60176. ground._maxZ = ground._height / 2;
  60177. ground._minX = -ground._maxX;
  60178. ground._minZ = -ground._maxZ;
  60179. var vertexData = BABYLON.VertexData.CreateGround(options);
  60180. vertexData.applyToMesh(ground, options.updatable);
  60181. ground._setReady(true);
  60182. return ground;
  60183. };
  60184. /**
  60185. * Creates a tiled ground mesh
  60186. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60187. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60188. * * 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
  60189. * * 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
  60190. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60191. * @param name defines the name of the mesh
  60192. * @param options defines the options used to create the mesh
  60193. * @param scene defines the hosting scene
  60194. * @returns the tiled ground mesh
  60195. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60196. */
  60197. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60198. var tiledGround = new BABYLON.Mesh(name, scene);
  60199. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60200. vertexData.applyToMesh(tiledGround, options.updatable);
  60201. return tiledGround;
  60202. };
  60203. /**
  60204. * Creates a ground mesh from a height map
  60205. * * The parameter `url` sets the URL of the height map image resource.
  60206. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60207. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60208. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60209. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60210. * * 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.
  60211. * * 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).
  60212. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60213. * @param name defines the name of the mesh
  60214. * @param url defines the url to the height map
  60215. * @param options defines the options used to create the mesh
  60216. * @param scene defines the hosting scene
  60217. * @returns the ground mesh
  60218. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60219. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60220. */
  60221. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60222. var width = options.width || 10.0;
  60223. var height = options.height || 10.0;
  60224. var subdivisions = options.subdivisions || 1 | 0;
  60225. var minHeight = options.minHeight || 0.0;
  60226. var maxHeight = options.maxHeight || 1.0;
  60227. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60228. var updatable = options.updatable;
  60229. var onReady = options.onReady;
  60230. var ground = new BABYLON.GroundMesh(name, scene);
  60231. ground._subdivisionsX = subdivisions;
  60232. ground._subdivisionsY = subdivisions;
  60233. ground._width = width;
  60234. ground._height = height;
  60235. ground._maxX = ground._width / 2.0;
  60236. ground._maxZ = ground._height / 2.0;
  60237. ground._minX = -ground._maxX;
  60238. ground._minZ = -ground._maxZ;
  60239. ground._setReady(false);
  60240. var onload = function (img) {
  60241. // Getting height map data
  60242. var canvas = document.createElement("canvas");
  60243. var context = canvas.getContext("2d");
  60244. if (!context) {
  60245. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60246. }
  60247. if (scene.isDisposed) {
  60248. return;
  60249. }
  60250. var bufferWidth = img.width;
  60251. var bufferHeight = img.height;
  60252. canvas.width = bufferWidth;
  60253. canvas.height = bufferHeight;
  60254. context.drawImage(img, 0, 0);
  60255. // Create VertexData from map data
  60256. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60257. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60258. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60259. width: width, height: height,
  60260. subdivisions: subdivisions,
  60261. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60262. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60263. });
  60264. vertexData.applyToMesh(ground, updatable);
  60265. //execute ready callback, if set
  60266. if (onReady) {
  60267. onReady(ground);
  60268. }
  60269. ground._setReady(true);
  60270. };
  60271. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60272. return ground;
  60273. };
  60274. /**
  60275. * Creates a polygon mesh
  60276. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60277. * * 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
  60278. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60279. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60280. * * 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)
  60281. * * Remember you can only change the shape positions, not their number when updating a polygon
  60282. * @param name defines the name of the mesh
  60283. * @param options defines the options used to create the mesh
  60284. * @param scene defines the hosting scene
  60285. * @returns the polygon mesh
  60286. */
  60287. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60288. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60289. var shape = options.shape;
  60290. var holes = options.holes || [];
  60291. var depth = options.depth || 0;
  60292. var contours = [];
  60293. var hole = [];
  60294. for (var i = 0; i < shape.length; i++) {
  60295. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60296. }
  60297. var epsilon = 0.00000001;
  60298. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60299. contours.pop();
  60300. }
  60301. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60302. for (var hNb = 0; hNb < holes.length; hNb++) {
  60303. hole = [];
  60304. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60305. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60306. }
  60307. polygonTriangulation.addHole(hole);
  60308. }
  60309. var polygon = polygonTriangulation.build(options.updatable, depth);
  60310. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60311. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60312. vertexData.applyToMesh(polygon, options.updatable);
  60313. return polygon;
  60314. };
  60315. ;
  60316. /**
  60317. * Creates an extruded polygon mesh, with depth in the Y direction.
  60318. * * 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)
  60319. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60320. * @param name defines the name of the mesh
  60321. * @param options defines the options used to create the mesh
  60322. * @param scene defines the hosting scene
  60323. * @returns the polygon mesh
  60324. */
  60325. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60326. return MeshBuilder.CreatePolygon(name, options, scene);
  60327. };
  60328. ;
  60329. /**
  60330. * Creates a tube mesh.
  60331. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60332. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60333. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60334. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60335. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60336. * * 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)
  60337. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60338. * * 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
  60339. * * 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
  60340. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60341. * * 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
  60342. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60343. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60344. * @param name defines the name of the mesh
  60345. * @param options defines the options used to create the mesh
  60346. * @param scene defines the hosting scene
  60347. * @returns the tube mesh
  60348. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60349. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60350. */
  60351. MeshBuilder.CreateTube = function (name, options, scene) {
  60352. var path = options.path;
  60353. var instance = options.instance;
  60354. var radius = 1.0;
  60355. if (instance) {
  60356. radius = instance.radius;
  60357. }
  60358. if (options.radius !== undefined) {
  60359. radius = options.radius;
  60360. }
  60361. ;
  60362. var tessellation = options.tessellation || 64 | 0;
  60363. var radiusFunction = options.radiusFunction || null;
  60364. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60365. var invertUV = options.invertUV || false;
  60366. var updatable = options.updatable;
  60367. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60368. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60369. // tube geometry
  60370. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60371. var tangents = path3D.getTangents();
  60372. var normals = path3D.getNormals();
  60373. var distances = path3D.getDistances();
  60374. var pi2 = Math.PI * 2;
  60375. var step = pi2 / tessellation * arc;
  60376. var returnRadius = function () { return radius; };
  60377. var radiusFunctionFinal = radiusFunction || returnRadius;
  60378. var circlePath;
  60379. var rad;
  60380. var normal;
  60381. var rotated;
  60382. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60383. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60384. for (var i = 0; i < path.length; i++) {
  60385. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60386. circlePath = Array(); // current circle array
  60387. normal = normals[i]; // current normal
  60388. for (var t = 0; t < tessellation; t++) {
  60389. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60390. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60391. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60392. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60393. circlePath[t] = rotated;
  60394. }
  60395. circlePaths[index] = circlePath;
  60396. index++;
  60397. }
  60398. // cap
  60399. var capPath = function (nbPoints, pathIndex) {
  60400. var pointCap = Array();
  60401. for (var i = 0; i < nbPoints; i++) {
  60402. pointCap.push(path[pathIndex]);
  60403. }
  60404. return pointCap;
  60405. };
  60406. switch (cap) {
  60407. case BABYLON.Mesh.NO_CAP:
  60408. break;
  60409. case BABYLON.Mesh.CAP_START:
  60410. circlePaths[0] = capPath(tessellation, 0);
  60411. circlePaths[1] = circlePaths[2].slice(0);
  60412. break;
  60413. case BABYLON.Mesh.CAP_END:
  60414. circlePaths[index] = circlePaths[index - 1].slice(0);
  60415. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60416. break;
  60417. case BABYLON.Mesh.CAP_ALL:
  60418. circlePaths[0] = capPath(tessellation, 0);
  60419. circlePaths[1] = circlePaths[2].slice(0);
  60420. circlePaths[index] = circlePaths[index - 1].slice(0);
  60421. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60422. break;
  60423. default:
  60424. break;
  60425. }
  60426. return circlePaths;
  60427. };
  60428. var path3D;
  60429. var pathArray;
  60430. if (instance) {
  60431. var arc = options.arc || instance.arc;
  60432. path3D = (instance.path3D).update(path);
  60433. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60434. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60435. instance.path3D = path3D;
  60436. instance.pathArray = pathArray;
  60437. instance.arc = arc;
  60438. instance.radius = radius;
  60439. return instance;
  60440. }
  60441. // tube creation
  60442. path3D = new BABYLON.Path3D(path);
  60443. var newPathArray = new Array();
  60444. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60445. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60446. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60447. tube.pathArray = pathArray;
  60448. tube.path3D = path3D;
  60449. tube.tessellation = tessellation;
  60450. tube.cap = cap;
  60451. tube.arc = options.arc;
  60452. tube.radius = radius;
  60453. return tube;
  60454. };
  60455. /**
  60456. * Creates a polyhedron mesh
  60457. * * 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
  60458. * * The parameter `size` (positive float, default 1) sets the polygon size
  60459. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60460. * * 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`
  60461. * * 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
  60462. * * 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)`)
  60463. * * 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
  60464. * * 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
  60465. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60466. * * 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
  60467. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60468. * @param name defines the name of the mesh
  60469. * @param options defines the options used to create the mesh
  60470. * @param scene defines the hosting scene
  60471. * @returns the polyhedron mesh
  60472. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60473. */
  60474. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60475. var polyhedron = new BABYLON.Mesh(name, scene);
  60476. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60477. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60478. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60479. vertexData.applyToMesh(polyhedron, options.updatable);
  60480. return polyhedron;
  60481. };
  60482. /**
  60483. * Creates a decal mesh.
  60484. * 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
  60485. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60486. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60487. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60488. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60489. * @param name defines the name of the mesh
  60490. * @param sourceMesh defines the mesh where the decal must be applied
  60491. * @param options defines the options used to create the mesh
  60492. * @param scene defines the hosting scene
  60493. * @returns the decal mesh
  60494. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60495. */
  60496. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60497. var indices = sourceMesh.getIndices();
  60498. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60499. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60500. var position = options.position || BABYLON.Vector3.Zero();
  60501. var normal = options.normal || BABYLON.Vector3.Up();
  60502. var size = options.size || BABYLON.Vector3.One();
  60503. var angle = options.angle || 0;
  60504. // Getting correct rotation
  60505. if (!normal) {
  60506. var target = new BABYLON.Vector3(0, 0, 1);
  60507. var camera = sourceMesh.getScene().activeCamera;
  60508. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60509. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60510. }
  60511. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60512. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60513. var pitch = Math.atan2(normal.y, len);
  60514. // Matrix
  60515. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60516. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60517. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60518. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60519. var vertexData = new BABYLON.VertexData();
  60520. vertexData.indices = [];
  60521. vertexData.positions = [];
  60522. vertexData.normals = [];
  60523. vertexData.uvs = [];
  60524. var currentVertexDataIndex = 0;
  60525. var extractDecalVector3 = function (indexId) {
  60526. var result = new BABYLON.PositionNormalVertex();
  60527. if (!indices || !positions || !normals) {
  60528. return result;
  60529. }
  60530. var vertexId = indices[indexId];
  60531. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60532. // Send vector to decal local world
  60533. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60534. // Get normal
  60535. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60536. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60537. return result;
  60538. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60539. var clip = function (vertices, axis) {
  60540. if (vertices.length === 0) {
  60541. return vertices;
  60542. }
  60543. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60544. var clipVertices = function (v0, v1) {
  60545. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60546. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60547. };
  60548. var result = new Array();
  60549. for (var index = 0; index < vertices.length; index += 3) {
  60550. var v1Out;
  60551. var v2Out;
  60552. var v3Out;
  60553. var total = 0;
  60554. var nV1 = null;
  60555. var nV2 = null;
  60556. var nV3 = null;
  60557. var nV4 = null;
  60558. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60559. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60560. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60561. v1Out = d1 > 0;
  60562. v2Out = d2 > 0;
  60563. v3Out = d3 > 0;
  60564. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60565. switch (total) {
  60566. case 0:
  60567. result.push(vertices[index]);
  60568. result.push(vertices[index + 1]);
  60569. result.push(vertices[index + 2]);
  60570. break;
  60571. case 1:
  60572. if (v1Out) {
  60573. nV1 = vertices[index + 1];
  60574. nV2 = vertices[index + 2];
  60575. nV3 = clipVertices(vertices[index], nV1);
  60576. nV4 = clipVertices(vertices[index], nV2);
  60577. }
  60578. if (v2Out) {
  60579. nV1 = vertices[index];
  60580. nV2 = vertices[index + 2];
  60581. nV3 = clipVertices(vertices[index + 1], nV1);
  60582. nV4 = clipVertices(vertices[index + 1], nV2);
  60583. result.push(nV3);
  60584. result.push(nV2.clone());
  60585. result.push(nV1.clone());
  60586. result.push(nV2.clone());
  60587. result.push(nV3.clone());
  60588. result.push(nV4);
  60589. break;
  60590. }
  60591. if (v3Out) {
  60592. nV1 = vertices[index];
  60593. nV2 = vertices[index + 1];
  60594. nV3 = clipVertices(vertices[index + 2], nV1);
  60595. nV4 = clipVertices(vertices[index + 2], nV2);
  60596. }
  60597. if (nV1 && nV2 && nV3 && nV4) {
  60598. result.push(nV1.clone());
  60599. result.push(nV2.clone());
  60600. result.push(nV3);
  60601. result.push(nV4);
  60602. result.push(nV3.clone());
  60603. result.push(nV2.clone());
  60604. }
  60605. break;
  60606. case 2:
  60607. if (!v1Out) {
  60608. nV1 = vertices[index].clone();
  60609. nV2 = clipVertices(nV1, vertices[index + 1]);
  60610. nV3 = clipVertices(nV1, vertices[index + 2]);
  60611. result.push(nV1);
  60612. result.push(nV2);
  60613. result.push(nV3);
  60614. }
  60615. if (!v2Out) {
  60616. nV1 = vertices[index + 1].clone();
  60617. nV2 = clipVertices(nV1, vertices[index + 2]);
  60618. nV3 = clipVertices(nV1, vertices[index]);
  60619. result.push(nV1);
  60620. result.push(nV2);
  60621. result.push(nV3);
  60622. }
  60623. if (!v3Out) {
  60624. nV1 = vertices[index + 2].clone();
  60625. nV2 = clipVertices(nV1, vertices[index]);
  60626. nV3 = clipVertices(nV1, vertices[index + 1]);
  60627. result.push(nV1);
  60628. result.push(nV2);
  60629. result.push(nV3);
  60630. }
  60631. break;
  60632. case 3:
  60633. break;
  60634. }
  60635. }
  60636. return result;
  60637. };
  60638. for (var index = 0; index < indices.length; index += 3) {
  60639. var faceVertices = new Array();
  60640. faceVertices.push(extractDecalVector3(index));
  60641. faceVertices.push(extractDecalVector3(index + 1));
  60642. faceVertices.push(extractDecalVector3(index + 2));
  60643. // Clip
  60644. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60645. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60646. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60647. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60648. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60649. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60650. if (faceVertices.length === 0) {
  60651. continue;
  60652. }
  60653. // Add UVs and get back to world
  60654. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60655. var vertex = faceVertices[vIndex];
  60656. //TODO check for Int32Array | Uint32Array | Uint16Array
  60657. vertexData.indices.push(currentVertexDataIndex);
  60658. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60659. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60660. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60661. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60662. currentVertexDataIndex++;
  60663. }
  60664. }
  60665. // Return mesh
  60666. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60667. vertexData.applyToMesh(decal);
  60668. decal.position = position.clone();
  60669. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60670. return decal;
  60671. };
  60672. // Privates
  60673. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60674. // extrusion geometry
  60675. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60676. var tangents = path3D.getTangents();
  60677. var normals = path3D.getNormals();
  60678. var binormals = path3D.getBinormals();
  60679. var distances = path3D.getDistances();
  60680. var angle = 0;
  60681. var returnScale = function () { return scale !== null ? scale : 1; };
  60682. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60683. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60684. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60685. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60686. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60687. for (var i = 0; i < curve.length; i++) {
  60688. var shapePath = new Array();
  60689. var angleStep = rotate(i, distances[i]);
  60690. var scaleRatio = scl(i, distances[i]);
  60691. for (var p = 0; p < shape.length; p++) {
  60692. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60693. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60694. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60695. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60696. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60697. shapePath[p] = rotated;
  60698. }
  60699. shapePaths[index] = shapePath;
  60700. angle += angleStep;
  60701. index++;
  60702. }
  60703. // cap
  60704. var capPath = function (shapePath) {
  60705. var pointCap = Array();
  60706. var barycenter = BABYLON.Vector3.Zero();
  60707. var i;
  60708. for (i = 0; i < shapePath.length; i++) {
  60709. barycenter.addInPlace(shapePath[i]);
  60710. }
  60711. barycenter.scaleInPlace(1.0 / shapePath.length);
  60712. for (i = 0; i < shapePath.length; i++) {
  60713. pointCap.push(barycenter);
  60714. }
  60715. return pointCap;
  60716. };
  60717. switch (cap) {
  60718. case BABYLON.Mesh.NO_CAP:
  60719. break;
  60720. case BABYLON.Mesh.CAP_START:
  60721. shapePaths[0] = capPath(shapePaths[2]);
  60722. shapePaths[1] = shapePaths[2];
  60723. break;
  60724. case BABYLON.Mesh.CAP_END:
  60725. shapePaths[index] = shapePaths[index - 1];
  60726. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60727. break;
  60728. case BABYLON.Mesh.CAP_ALL:
  60729. shapePaths[0] = capPath(shapePaths[2]);
  60730. shapePaths[1] = shapePaths[2];
  60731. shapePaths[index] = shapePaths[index - 1];
  60732. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60733. break;
  60734. default:
  60735. break;
  60736. }
  60737. return shapePaths;
  60738. };
  60739. var path3D;
  60740. var pathArray;
  60741. if (instance) {
  60742. path3D = (instance.path3D).update(curve);
  60743. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60744. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60745. return instance;
  60746. }
  60747. // extruded shape creation
  60748. path3D = new BABYLON.Path3D(curve);
  60749. var newShapePaths = new Array();
  60750. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60751. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60752. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60753. extrudedGeneric.pathArray = pathArray;
  60754. extrudedGeneric.path3D = path3D;
  60755. extrudedGeneric.cap = cap;
  60756. return extrudedGeneric;
  60757. };
  60758. return MeshBuilder;
  60759. }());
  60760. BABYLON.MeshBuilder = MeshBuilder;
  60761. })(BABYLON || (BABYLON = {}));
  60762. //# sourceMappingURL=babylon.meshBuilder.js.map
  60763. "use strict";
  60764. var BABYLON;
  60765. (function (BABYLON) {
  60766. /**
  60767. * Draco compression (https://google.github.io/draco/)
  60768. */
  60769. var DracoCompression = /** @class */ (function () {
  60770. /**
  60771. * Constructor
  60772. */
  60773. function DracoCompression() {
  60774. }
  60775. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  60776. /**
  60777. * Returns true if the decoder is available.
  60778. */
  60779. get: function () {
  60780. return (typeof DracoDecoderModule !== "undefined" ||
  60781. (typeof WebAssembly === "object" && !!DracoCompression.Configuration.decoderWasm) ||
  60782. !!DracoCompression.Configuration.decoder);
  60783. },
  60784. enumerable: true,
  60785. configurable: true
  60786. });
  60787. /**
  60788. * Stop all async operations and release resources.
  60789. */
  60790. DracoCompression.prototype.dispose = function () {
  60791. };
  60792. /**
  60793. * Decode Draco compressed mesh data to vertex data.
  60794. * @param data The array buffer view for the Draco compression data
  60795. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  60796. * @returns A promise that resolves with the decoded vertex data
  60797. */
  60798. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  60799. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  60800. var module = wrappedModule.module;
  60801. var vertexData = new BABYLON.VertexData();
  60802. var buffer = new module.DecoderBuffer();
  60803. buffer.Init(data, data.byteLength);
  60804. var decoder = new module.Decoder();
  60805. var geometry;
  60806. var status;
  60807. try {
  60808. var type = decoder.GetEncodedGeometryType(buffer);
  60809. switch (type) {
  60810. case module.TRIANGULAR_MESH:
  60811. geometry = new module.Mesh();
  60812. status = decoder.DecodeBufferToMesh(buffer, geometry);
  60813. break;
  60814. case module.POINT_CLOUD:
  60815. geometry = new module.PointCloud();
  60816. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  60817. break;
  60818. default:
  60819. throw new Error("Invalid geometry type " + type);
  60820. }
  60821. if (!status.ok() || !geometry.ptr) {
  60822. throw new Error(status.error_msg());
  60823. }
  60824. var numPoints = geometry.num_points();
  60825. if (type === module.TRIANGULAR_MESH) {
  60826. var numFaces = geometry.num_faces();
  60827. var faceIndices = new module.DracoInt32Array();
  60828. try {
  60829. var indices = new Uint32Array(numFaces * 3);
  60830. for (var i = 0; i < numFaces; i++) {
  60831. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  60832. var offset = i * 3;
  60833. indices[offset + 0] = faceIndices.GetValue(0);
  60834. indices[offset + 1] = faceIndices.GetValue(1);
  60835. indices[offset + 2] = faceIndices.GetValue(2);
  60836. }
  60837. vertexData.indices = indices;
  60838. }
  60839. finally {
  60840. module.destroy(faceIndices);
  60841. }
  60842. }
  60843. for (var kind in attributes) {
  60844. var uniqueId = attributes[kind];
  60845. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  60846. var dracoData = new module.DracoFloat32Array();
  60847. try {
  60848. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  60849. var babylonData = new Float32Array(numPoints * attribute.num_components());
  60850. for (var i = 0; i < babylonData.length; i++) {
  60851. babylonData[i] = dracoData.GetValue(i);
  60852. }
  60853. vertexData.set(babylonData, kind);
  60854. }
  60855. finally {
  60856. module.destroy(dracoData);
  60857. }
  60858. }
  60859. }
  60860. finally {
  60861. if (geometry) {
  60862. module.destroy(geometry);
  60863. }
  60864. module.destroy(decoder);
  60865. module.destroy(buffer);
  60866. }
  60867. return vertexData;
  60868. });
  60869. };
  60870. DracoCompression._GetDecoderModule = function () {
  60871. if (!DracoCompression._DecoderModulePromise) {
  60872. var promise = void 0;
  60873. var config_1 = {};
  60874. if (typeof DracoDecoderModule !== "undefined") {
  60875. promise = Promise.resolve();
  60876. }
  60877. else if (typeof WebAssembly === "object" && DracoCompression.Configuration.decoderWasm) {
  60878. promise = Promise.all([
  60879. DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoderWasm.wrapperUrl),
  60880. DracoCompression._LoadFileAsync(DracoCompression.Configuration.decoderWasm.binaryUrl).then(function (data) {
  60881. config_1.wasmBinary = data;
  60882. })
  60883. ]);
  60884. }
  60885. else if (DracoCompression.Configuration.decoder) {
  60886. promise = DracoCompression._LoadScriptAsync(DracoCompression.Configuration.decoder.url);
  60887. }
  60888. else {
  60889. throw new Error("Invalid decoder configuration");
  60890. }
  60891. DracoCompression._DecoderModulePromise = promise.then(function () {
  60892. return new Promise(function (resolve) {
  60893. config_1.onModuleLoaded = function (decoderModule) {
  60894. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  60895. resolve({ module: decoderModule });
  60896. };
  60897. DracoDecoderModule(config_1);
  60898. });
  60899. });
  60900. }
  60901. return DracoCompression._DecoderModulePromise;
  60902. };
  60903. DracoCompression._LoadScriptAsync = function (url) {
  60904. return new Promise(function (resolve, reject) {
  60905. BABYLON.Tools.LoadScript(url, function () {
  60906. resolve();
  60907. }, function (message) {
  60908. reject(new Error(message));
  60909. });
  60910. });
  60911. };
  60912. DracoCompression._LoadFileAsync = function (url) {
  60913. return new Promise(function (resolve, reject) {
  60914. BABYLON.Tools.LoadFile(url, function (data) {
  60915. resolve(data);
  60916. }, undefined, undefined, true, function (request, exception) {
  60917. reject(exception);
  60918. });
  60919. });
  60920. };
  60921. DracoCompression._GetDefaultConfig = function () {
  60922. var configuration = {
  60923. decoder: null,
  60924. decoderWasm: null
  60925. };
  60926. if (BABYLON.Tools.IsWindowObjectExist()) {
  60927. var decoderUrl = null;
  60928. var decoderWasmBinaryUrl = null;
  60929. var decoderWasmWrapperUrl = null;
  60930. for (var i = 0; i < document.scripts.length; i++) {
  60931. var type = document.scripts[i].type;
  60932. var src = document.scripts[i].src;
  60933. switch (type) {
  60934. case "text/x-draco-decoder": {
  60935. decoderUrl = src;
  60936. break;
  60937. }
  60938. case "text/x-draco-decoder-wasm-binary": {
  60939. decoderWasmBinaryUrl = src;
  60940. break;
  60941. }
  60942. case "text/x-draco-decoder-wasm-wrapper": {
  60943. decoderWasmWrapperUrl = src;
  60944. break;
  60945. }
  60946. }
  60947. }
  60948. if (decoderUrl) {
  60949. configuration.decoder = {
  60950. url: decoderUrl
  60951. };
  60952. }
  60953. if (decoderWasmWrapperUrl && decoderWasmBinaryUrl) {
  60954. configuration.decoderWasm = {
  60955. binaryUrl: decoderWasmBinaryUrl,
  60956. wrapperUrl: decoderWasmWrapperUrl
  60957. };
  60958. }
  60959. }
  60960. return configuration;
  60961. };
  60962. /**
  60963. * Gets the configuration.
  60964. */
  60965. DracoCompression.Configuration = DracoCompression._GetDefaultConfig();
  60966. return DracoCompression;
  60967. }());
  60968. BABYLON.DracoCompression = DracoCompression;
  60969. })(BABYLON || (BABYLON = {}));
  60970. //# sourceMappingURL=babylon.dracoCompression.js.map
  60971. "use strict";
  60972. var BABYLON;
  60973. (function (BABYLON) {
  60974. var AudioEngine = /** @class */ (function () {
  60975. function AudioEngine() {
  60976. this._audioContext = null;
  60977. this._audioContextInitialized = false;
  60978. this.canUseWebAudio = false;
  60979. this.WarnedWebAudioUnsupported = false;
  60980. this.unlocked = false;
  60981. this.isMP3supported = false;
  60982. this.isOGGsupported = false;
  60983. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60984. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60985. this.canUseWebAudio = true;
  60986. }
  60987. var audioElem = document.createElement('audio');
  60988. try {
  60989. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60990. this.isMP3supported = true;
  60991. }
  60992. }
  60993. catch (e) {
  60994. // protect error during capability check.
  60995. }
  60996. try {
  60997. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60998. this.isOGGsupported = true;
  60999. }
  61000. }
  61001. catch (e) {
  61002. // protect error during capability check.
  61003. }
  61004. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61005. this._unlockiOSaudio();
  61006. }
  61007. else {
  61008. this.unlocked = true;
  61009. }
  61010. }
  61011. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61012. get: function () {
  61013. if (!this._audioContextInitialized) {
  61014. this._initializeAudioContext();
  61015. }
  61016. return this._audioContext;
  61017. },
  61018. enumerable: true,
  61019. configurable: true
  61020. });
  61021. AudioEngine.prototype._unlockiOSaudio = function () {
  61022. var _this = this;
  61023. var unlockaudio = function () {
  61024. if (!_this.audioContext) {
  61025. return;
  61026. }
  61027. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61028. var source = _this.audioContext.createBufferSource();
  61029. source.buffer = buffer;
  61030. source.connect(_this.audioContext.destination);
  61031. source.start(0);
  61032. setTimeout(function () {
  61033. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61034. _this.unlocked = true;
  61035. window.removeEventListener('touchend', unlockaudio, false);
  61036. if (_this.onAudioUnlocked) {
  61037. _this.onAudioUnlocked();
  61038. }
  61039. }
  61040. }, 0);
  61041. };
  61042. window.addEventListener('touchend', unlockaudio, false);
  61043. };
  61044. AudioEngine.prototype._initializeAudioContext = function () {
  61045. try {
  61046. if (this.canUseWebAudio) {
  61047. this._audioContext = new AudioContext();
  61048. // create a global volume gain node
  61049. this.masterGain = this._audioContext.createGain();
  61050. this.masterGain.gain.value = 1;
  61051. this.masterGain.connect(this._audioContext.destination);
  61052. this._audioContextInitialized = true;
  61053. }
  61054. }
  61055. catch (e) {
  61056. this.canUseWebAudio = false;
  61057. BABYLON.Tools.Error("Web Audio: " + e.message);
  61058. }
  61059. };
  61060. AudioEngine.prototype.dispose = function () {
  61061. if (this.canUseWebAudio && this._audioContextInitialized) {
  61062. if (this._connectedAnalyser && this._audioContext) {
  61063. this._connectedAnalyser.stopDebugCanvas();
  61064. this._connectedAnalyser.dispose();
  61065. this.masterGain.disconnect();
  61066. this.masterGain.connect(this._audioContext.destination);
  61067. this._connectedAnalyser = null;
  61068. }
  61069. this.masterGain.gain.value = 1;
  61070. }
  61071. this.WarnedWebAudioUnsupported = false;
  61072. };
  61073. AudioEngine.prototype.getGlobalVolume = function () {
  61074. if (this.canUseWebAudio && this._audioContextInitialized) {
  61075. return this.masterGain.gain.value;
  61076. }
  61077. else {
  61078. return -1;
  61079. }
  61080. };
  61081. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61082. if (this.canUseWebAudio && this._audioContextInitialized) {
  61083. this.masterGain.gain.value = newVolume;
  61084. }
  61085. };
  61086. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61087. if (this._connectedAnalyser) {
  61088. this._connectedAnalyser.stopDebugCanvas();
  61089. }
  61090. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61091. this._connectedAnalyser = analyser;
  61092. this.masterGain.disconnect();
  61093. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61094. }
  61095. };
  61096. return AudioEngine;
  61097. }());
  61098. BABYLON.AudioEngine = AudioEngine;
  61099. })(BABYLON || (BABYLON = {}));
  61100. //# sourceMappingURL=babylon.audioEngine.js.map
  61101. "use strict";
  61102. var BABYLON;
  61103. (function (BABYLON) {
  61104. var Sound = /** @class */ (function () {
  61105. /**
  61106. * Create a sound and attach it to a scene
  61107. * @param name Name of your sound
  61108. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61109. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61110. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61111. */
  61112. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61113. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61114. var _this = this;
  61115. this.autoplay = false;
  61116. this.loop = false;
  61117. this.useCustomAttenuation = false;
  61118. this.spatialSound = false;
  61119. this.refDistance = 1;
  61120. this.rolloffFactor = 1;
  61121. this.maxDistance = 100;
  61122. this.distanceModel = "linear";
  61123. this._panningModel = "equalpower";
  61124. this._playbackRate = 1;
  61125. this._streaming = false;
  61126. this._startTime = 0;
  61127. this._startOffset = 0;
  61128. this._position = BABYLON.Vector3.Zero();
  61129. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61130. this._volume = 1;
  61131. this._isReadyToPlay = false;
  61132. this.isPlaying = false;
  61133. this.isPaused = false;
  61134. this._isDirectional = false;
  61135. // Used if you'd like to create a directional sound.
  61136. // If not set, the sound will be omnidirectional
  61137. this._coneInnerAngle = 360;
  61138. this._coneOuterAngle = 360;
  61139. this._coneOuterGain = 0;
  61140. this._isOutputConnected = false;
  61141. this._urlType = "Unknown";
  61142. this.name = name;
  61143. this._scene = scene;
  61144. this._readyToPlayCallback = readyToPlayCallback;
  61145. // Default custom attenuation function is a linear attenuation
  61146. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61147. if (currentDistance < maxDistance) {
  61148. return currentVolume * (1 - currentDistance / maxDistance);
  61149. }
  61150. else {
  61151. return 0;
  61152. }
  61153. };
  61154. if (options) {
  61155. this.autoplay = options.autoplay || false;
  61156. this.loop = options.loop || false;
  61157. // if volume === 0, we need another way to check this option
  61158. if (options.volume !== undefined) {
  61159. this._volume = options.volume;
  61160. }
  61161. this.spatialSound = options.spatialSound || false;
  61162. this.maxDistance = options.maxDistance || 100;
  61163. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61164. this.rolloffFactor = options.rolloffFactor || 1;
  61165. this.refDistance = options.refDistance || 1;
  61166. this.distanceModel = options.distanceModel || "linear";
  61167. this._playbackRate = options.playbackRate || 1;
  61168. this._streaming = options.streaming || false;
  61169. }
  61170. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61171. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61172. this._soundGain.gain.value = this._volume;
  61173. this._inputAudioNode = this._soundGain;
  61174. this._ouputAudioNode = this._soundGain;
  61175. if (this.spatialSound) {
  61176. this._createSpatialParameters();
  61177. }
  61178. this._scene.mainSoundTrack.AddSound(this);
  61179. var validParameter = true;
  61180. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61181. if (urlOrArrayBuffer) {
  61182. try {
  61183. if (typeof (urlOrArrayBuffer) === "string")
  61184. this._urlType = "String";
  61185. if (Array.isArray(urlOrArrayBuffer))
  61186. this._urlType = "Array";
  61187. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61188. this._urlType = "ArrayBuffer";
  61189. var urls = [];
  61190. var codecSupportedFound = false;
  61191. switch (this._urlType) {
  61192. case "ArrayBuffer":
  61193. if (urlOrArrayBuffer.byteLength > 0) {
  61194. codecSupportedFound = true;
  61195. this._soundLoaded(urlOrArrayBuffer);
  61196. }
  61197. break;
  61198. case "String":
  61199. urls.push(urlOrArrayBuffer);
  61200. case "Array":
  61201. if (urls.length === 0)
  61202. urls = urlOrArrayBuffer;
  61203. // If we found a supported format, we load it immediately and stop the loop
  61204. for (var i = 0; i < urls.length; i++) {
  61205. var url = urls[i];
  61206. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61207. codecSupportedFound = true;
  61208. }
  61209. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61210. codecSupportedFound = true;
  61211. }
  61212. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61213. codecSupportedFound = true;
  61214. }
  61215. if (url.indexOf("blob:") !== -1) {
  61216. codecSupportedFound = true;
  61217. }
  61218. if (codecSupportedFound) {
  61219. // Loading sound using XHR2
  61220. if (!this._streaming) {
  61221. this._scene._loadFile(url, function (data) {
  61222. _this._soundLoaded(data);
  61223. }, undefined, true, true, function (exception) {
  61224. if (exception) {
  61225. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61226. }
  61227. BABYLON.Tools.Error("Sound creation aborted.");
  61228. _this._scene.mainSoundTrack.RemoveSound(_this);
  61229. });
  61230. }
  61231. else {
  61232. this._htmlAudioElement = new Audio(url);
  61233. this._htmlAudioElement.controls = false;
  61234. this._htmlAudioElement.loop = this.loop;
  61235. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61236. this._htmlAudioElement.preload = "auto";
  61237. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61238. _this._isReadyToPlay = true;
  61239. if (_this.autoplay) {
  61240. _this.play();
  61241. }
  61242. if (_this._readyToPlayCallback) {
  61243. _this._readyToPlayCallback();
  61244. }
  61245. });
  61246. document.body.appendChild(this._htmlAudioElement);
  61247. }
  61248. break;
  61249. }
  61250. }
  61251. break;
  61252. default:
  61253. validParameter = false;
  61254. break;
  61255. }
  61256. if (!validParameter) {
  61257. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61258. }
  61259. else {
  61260. if (!codecSupportedFound) {
  61261. this._isReadyToPlay = true;
  61262. // Simulating a ready to play event to avoid breaking code path
  61263. if (this._readyToPlayCallback) {
  61264. window.setTimeout(function () {
  61265. if (_this._readyToPlayCallback) {
  61266. _this._readyToPlayCallback();
  61267. }
  61268. }, 1000);
  61269. }
  61270. }
  61271. }
  61272. }
  61273. catch (ex) {
  61274. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61275. this._scene.mainSoundTrack.RemoveSound(this);
  61276. }
  61277. }
  61278. }
  61279. else {
  61280. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61281. this._scene.mainSoundTrack.AddSound(this);
  61282. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61283. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61284. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61285. }
  61286. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61287. if (this._readyToPlayCallback) {
  61288. window.setTimeout(function () {
  61289. if (_this._readyToPlayCallback) {
  61290. _this._readyToPlayCallback();
  61291. }
  61292. }, 1000);
  61293. }
  61294. }
  61295. }
  61296. Sound.prototype.dispose = function () {
  61297. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61298. if (this.isPlaying) {
  61299. this.stop();
  61300. }
  61301. this._isReadyToPlay = false;
  61302. if (this.soundTrackId === -1) {
  61303. this._scene.mainSoundTrack.RemoveSound(this);
  61304. }
  61305. else {
  61306. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61307. }
  61308. if (this._soundGain) {
  61309. this._soundGain.disconnect();
  61310. this._soundGain = null;
  61311. }
  61312. if (this._soundPanner) {
  61313. this._soundPanner.disconnect();
  61314. this._soundPanner = null;
  61315. }
  61316. if (this._soundSource) {
  61317. this._soundSource.disconnect();
  61318. this._soundSource = null;
  61319. }
  61320. this._audioBuffer = null;
  61321. if (this._htmlAudioElement) {
  61322. this._htmlAudioElement.pause();
  61323. this._htmlAudioElement.src = "";
  61324. document.body.removeChild(this._htmlAudioElement);
  61325. }
  61326. if (this._connectedMesh && this._registerFunc) {
  61327. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61328. this._connectedMesh = null;
  61329. }
  61330. }
  61331. };
  61332. Sound.prototype.isReady = function () {
  61333. return this._isReadyToPlay;
  61334. };
  61335. Sound.prototype._soundLoaded = function (audioData) {
  61336. var _this = this;
  61337. if (!BABYLON.Engine.audioEngine.audioContext) {
  61338. return;
  61339. }
  61340. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61341. _this._audioBuffer = buffer;
  61342. _this._isReadyToPlay = true;
  61343. if (_this.autoplay) {
  61344. _this.play();
  61345. }
  61346. if (_this._readyToPlayCallback) {
  61347. _this._readyToPlayCallback();
  61348. }
  61349. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61350. };
  61351. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61353. this._audioBuffer = audioBuffer;
  61354. this._isReadyToPlay = true;
  61355. }
  61356. };
  61357. Sound.prototype.updateOptions = function (options) {
  61358. if (options) {
  61359. this.loop = options.loop || this.loop;
  61360. this.maxDistance = options.maxDistance || this.maxDistance;
  61361. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61362. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61363. this.refDistance = options.refDistance || this.refDistance;
  61364. this.distanceModel = options.distanceModel || this.distanceModel;
  61365. this._playbackRate = options.playbackRate || this._playbackRate;
  61366. this._updateSpatialParameters();
  61367. if (this.isPlaying) {
  61368. if (this._streaming) {
  61369. this._htmlAudioElement.playbackRate = this._playbackRate;
  61370. }
  61371. else {
  61372. if (this._soundSource) {
  61373. this._soundSource.playbackRate.value = this._playbackRate;
  61374. }
  61375. }
  61376. }
  61377. }
  61378. };
  61379. Sound.prototype._createSpatialParameters = function () {
  61380. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61381. if (this._scene.headphone) {
  61382. this._panningModel = "HRTF";
  61383. }
  61384. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61385. this._updateSpatialParameters();
  61386. this._soundPanner.connect(this._ouputAudioNode);
  61387. this._inputAudioNode = this._soundPanner;
  61388. }
  61389. };
  61390. Sound.prototype._updateSpatialParameters = function () {
  61391. if (this.spatialSound && this._soundPanner) {
  61392. if (this.useCustomAttenuation) {
  61393. // Tricks to disable in a way embedded Web Audio attenuation
  61394. this._soundPanner.distanceModel = "linear";
  61395. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61396. this._soundPanner.refDistance = 1;
  61397. this._soundPanner.rolloffFactor = 1;
  61398. this._soundPanner.panningModel = this._panningModel;
  61399. }
  61400. else {
  61401. this._soundPanner.distanceModel = this.distanceModel;
  61402. this._soundPanner.maxDistance = this.maxDistance;
  61403. this._soundPanner.refDistance = this.refDistance;
  61404. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61405. this._soundPanner.panningModel = this._panningModel;
  61406. }
  61407. }
  61408. };
  61409. Sound.prototype.switchPanningModelToHRTF = function () {
  61410. this._panningModel = "HRTF";
  61411. this._switchPanningModel();
  61412. };
  61413. Sound.prototype.switchPanningModelToEqualPower = function () {
  61414. this._panningModel = "equalpower";
  61415. this._switchPanningModel();
  61416. };
  61417. Sound.prototype._switchPanningModel = function () {
  61418. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61419. this._soundPanner.panningModel = this._panningModel;
  61420. }
  61421. };
  61422. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61423. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61424. if (this._isOutputConnected) {
  61425. this._ouputAudioNode.disconnect();
  61426. }
  61427. this._ouputAudioNode.connect(soundTrackAudioNode);
  61428. this._isOutputConnected = true;
  61429. }
  61430. };
  61431. /**
  61432. * Transform this sound into a directional source
  61433. * @param coneInnerAngle Size of the inner cone in degree
  61434. * @param coneOuterAngle Size of the outer cone in degree
  61435. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61436. */
  61437. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61438. if (coneOuterAngle < coneInnerAngle) {
  61439. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61440. return;
  61441. }
  61442. this._coneInnerAngle = coneInnerAngle;
  61443. this._coneOuterAngle = coneOuterAngle;
  61444. this._coneOuterGain = coneOuterGain;
  61445. this._isDirectional = true;
  61446. if (this.isPlaying && this.loop) {
  61447. this.stop();
  61448. this.play();
  61449. }
  61450. };
  61451. Sound.prototype.setPosition = function (newPosition) {
  61452. this._position = newPosition;
  61453. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61454. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61455. }
  61456. };
  61457. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61458. this._localDirection = newLocalDirection;
  61459. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61460. this._updateDirection();
  61461. }
  61462. };
  61463. Sound.prototype._updateDirection = function () {
  61464. if (!this._connectedMesh || !this._soundPanner) {
  61465. return;
  61466. }
  61467. var mat = this._connectedMesh.getWorldMatrix();
  61468. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61469. direction.normalize();
  61470. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61471. };
  61472. Sound.prototype.updateDistanceFromListener = function () {
  61473. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61474. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61475. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61476. }
  61477. };
  61478. Sound.prototype.setAttenuationFunction = function (callback) {
  61479. this._customAttenuationFunction = callback;
  61480. };
  61481. /**
  61482. * Play the sound
  61483. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61484. * @param offset (optional) Start the sound setting it at a specific time
  61485. */
  61486. Sound.prototype.play = function (time, offset) {
  61487. var _this = this;
  61488. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61489. try {
  61490. if (this._startOffset < 0) {
  61491. time = -this._startOffset;
  61492. this._startOffset = 0;
  61493. }
  61494. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61495. if (!this._soundSource || !this._streamingSource) {
  61496. if (this.spatialSound && this._soundPanner) {
  61497. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61498. if (this._isDirectional) {
  61499. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61500. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61501. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61502. if (this._connectedMesh) {
  61503. this._updateDirection();
  61504. }
  61505. else {
  61506. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61507. }
  61508. }
  61509. }
  61510. }
  61511. if (this._streaming) {
  61512. if (!this._streamingSource) {
  61513. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61514. this._htmlAudioElement.onended = function () { _this._onended(); };
  61515. this._htmlAudioElement.playbackRate = this._playbackRate;
  61516. }
  61517. this._streamingSource.disconnect();
  61518. this._streamingSource.connect(this._inputAudioNode);
  61519. this._htmlAudioElement.play();
  61520. }
  61521. else {
  61522. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61523. this._soundSource.buffer = this._audioBuffer;
  61524. this._soundSource.connect(this._inputAudioNode);
  61525. this._soundSource.loop = this.loop;
  61526. this._soundSource.playbackRate.value = this._playbackRate;
  61527. this._soundSource.onended = function () { _this._onended(); };
  61528. if (this._soundSource.buffer) {
  61529. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61530. }
  61531. }
  61532. this._startTime = startTime;
  61533. this.isPlaying = true;
  61534. this.isPaused = false;
  61535. }
  61536. catch (ex) {
  61537. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61538. }
  61539. }
  61540. };
  61541. Sound.prototype._onended = function () {
  61542. this.isPlaying = false;
  61543. if (this.onended) {
  61544. this.onended();
  61545. }
  61546. };
  61547. /**
  61548. * Stop the sound
  61549. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61550. */
  61551. Sound.prototype.stop = function (time) {
  61552. if (this.isPlaying) {
  61553. if (this._streaming) {
  61554. this._htmlAudioElement.pause();
  61555. // Test needed for Firefox or it will generate an Invalid State Error
  61556. if (this._htmlAudioElement.currentTime > 0) {
  61557. this._htmlAudioElement.currentTime = 0;
  61558. }
  61559. }
  61560. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61561. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61562. this._soundSource.stop(stopTime);
  61563. this._soundSource.onended = function () { };
  61564. if (!this.isPaused) {
  61565. this._startOffset = 0;
  61566. }
  61567. }
  61568. this.isPlaying = false;
  61569. }
  61570. };
  61571. Sound.prototype.pause = function () {
  61572. if (this.isPlaying) {
  61573. this.isPaused = true;
  61574. if (this._streaming) {
  61575. this._htmlAudioElement.pause();
  61576. }
  61577. else if (BABYLON.Engine.audioEngine.audioContext) {
  61578. this.stop(0);
  61579. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61580. }
  61581. }
  61582. };
  61583. Sound.prototype.setVolume = function (newVolume, time) {
  61584. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61585. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61586. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61587. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61588. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61589. }
  61590. else {
  61591. this._soundGain.gain.value = newVolume;
  61592. }
  61593. }
  61594. this._volume = newVolume;
  61595. };
  61596. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61597. this._playbackRate = newPlaybackRate;
  61598. if (this.isPlaying) {
  61599. if (this._streaming) {
  61600. this._htmlAudioElement.playbackRate = this._playbackRate;
  61601. }
  61602. else if (this._soundSource) {
  61603. this._soundSource.playbackRate.value = this._playbackRate;
  61604. }
  61605. }
  61606. };
  61607. Sound.prototype.getVolume = function () {
  61608. return this._volume;
  61609. };
  61610. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61611. var _this = this;
  61612. if (this._connectedMesh && this._registerFunc) {
  61613. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61614. this._registerFunc = null;
  61615. }
  61616. this._connectedMesh = meshToConnectTo;
  61617. if (!this.spatialSound) {
  61618. this.spatialSound = true;
  61619. this._createSpatialParameters();
  61620. if (this.isPlaying && this.loop) {
  61621. this.stop();
  61622. this.play();
  61623. }
  61624. }
  61625. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61626. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61627. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61628. };
  61629. Sound.prototype.detachFromMesh = function () {
  61630. if (this._connectedMesh && this._registerFunc) {
  61631. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61632. this._registerFunc = null;
  61633. this._connectedMesh = null;
  61634. }
  61635. };
  61636. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61637. if (!node.getBoundingInfo) {
  61638. return;
  61639. }
  61640. var mesh = node;
  61641. var boundingInfo = mesh.getBoundingInfo();
  61642. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61643. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61644. this._updateDirection();
  61645. }
  61646. };
  61647. Sound.prototype.clone = function () {
  61648. var _this = this;
  61649. if (!this._streaming) {
  61650. var setBufferAndRun = function () {
  61651. if (_this._isReadyToPlay) {
  61652. clonedSound._audioBuffer = _this.getAudioBuffer();
  61653. clonedSound._isReadyToPlay = true;
  61654. if (clonedSound.autoplay) {
  61655. clonedSound.play();
  61656. }
  61657. }
  61658. else {
  61659. window.setTimeout(setBufferAndRun, 300);
  61660. }
  61661. };
  61662. var currentOptions = {
  61663. autoplay: this.autoplay, loop: this.loop,
  61664. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61665. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61666. refDistance: this.refDistance, distanceModel: this.distanceModel
  61667. };
  61668. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61669. if (this.useCustomAttenuation) {
  61670. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61671. }
  61672. clonedSound.setPosition(this._position);
  61673. clonedSound.setPlaybackRate(this._playbackRate);
  61674. setBufferAndRun();
  61675. return clonedSound;
  61676. }
  61677. else {
  61678. return null;
  61679. }
  61680. };
  61681. Sound.prototype.getAudioBuffer = function () {
  61682. return this._audioBuffer;
  61683. };
  61684. Sound.prototype.serialize = function () {
  61685. var serializationObject = {
  61686. name: this.name,
  61687. url: this.name,
  61688. autoplay: this.autoplay,
  61689. loop: this.loop,
  61690. volume: this._volume,
  61691. spatialSound: this.spatialSound,
  61692. maxDistance: this.maxDistance,
  61693. rolloffFactor: this.rolloffFactor,
  61694. refDistance: this.refDistance,
  61695. distanceModel: this.distanceModel,
  61696. playbackRate: this._playbackRate,
  61697. panningModel: this._panningModel,
  61698. soundTrackId: this.soundTrackId
  61699. };
  61700. if (this.spatialSound) {
  61701. if (this._connectedMesh)
  61702. serializationObject.connectedMeshId = this._connectedMesh.id;
  61703. serializationObject.position = this._position.asArray();
  61704. serializationObject.refDistance = this.refDistance;
  61705. serializationObject.distanceModel = this.distanceModel;
  61706. serializationObject.isDirectional = this._isDirectional;
  61707. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61708. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61709. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61710. serializationObject.coneOuterGain = this._coneOuterGain;
  61711. }
  61712. return serializationObject;
  61713. };
  61714. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61715. var soundName = parsedSound.name;
  61716. var soundUrl;
  61717. if (parsedSound.url) {
  61718. soundUrl = rootUrl + parsedSound.url;
  61719. }
  61720. else {
  61721. soundUrl = rootUrl + soundName;
  61722. }
  61723. var options = {
  61724. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61725. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61726. rolloffFactor: parsedSound.rolloffFactor,
  61727. refDistance: parsedSound.refDistance,
  61728. distanceModel: parsedSound.distanceModel,
  61729. playbackRate: parsedSound.playbackRate
  61730. };
  61731. var newSound;
  61732. if (!sourceSound) {
  61733. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61734. scene._addPendingData(newSound);
  61735. }
  61736. else {
  61737. var setBufferAndRun = function () {
  61738. if (sourceSound._isReadyToPlay) {
  61739. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61740. newSound._isReadyToPlay = true;
  61741. if (newSound.autoplay) {
  61742. newSound.play();
  61743. }
  61744. }
  61745. else {
  61746. window.setTimeout(setBufferAndRun, 300);
  61747. }
  61748. };
  61749. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61750. setBufferAndRun();
  61751. }
  61752. if (parsedSound.position) {
  61753. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61754. newSound.setPosition(soundPosition);
  61755. }
  61756. if (parsedSound.isDirectional) {
  61757. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61758. if (parsedSound.localDirectionToMesh) {
  61759. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61760. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61761. }
  61762. }
  61763. if (parsedSound.connectedMeshId) {
  61764. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61765. if (connectedMesh) {
  61766. newSound.attachToMesh(connectedMesh);
  61767. }
  61768. }
  61769. return newSound;
  61770. };
  61771. return Sound;
  61772. }());
  61773. BABYLON.Sound = Sound;
  61774. })(BABYLON || (BABYLON = {}));
  61775. //# sourceMappingURL=babylon.sound.js.map
  61776. "use strict";
  61777. var BABYLON;
  61778. (function (BABYLON) {
  61779. var SoundTrack = /** @class */ (function () {
  61780. function SoundTrack(scene, options) {
  61781. this.id = -1;
  61782. this._isMainTrack = false;
  61783. this._isInitialized = false;
  61784. this._scene = scene;
  61785. this.soundCollection = new Array();
  61786. this._options = options;
  61787. if (!this._isMainTrack) {
  61788. this._scene.soundTracks.push(this);
  61789. this.id = this._scene.soundTracks.length - 1;
  61790. }
  61791. }
  61792. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  61793. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61794. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  61795. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  61796. if (this._options) {
  61797. if (this._options.volume) {
  61798. this._outputAudioNode.gain.value = this._options.volume;
  61799. }
  61800. if (this._options.mainTrack) {
  61801. this._isMainTrack = this._options.mainTrack;
  61802. }
  61803. }
  61804. this._isInitialized = true;
  61805. }
  61806. };
  61807. SoundTrack.prototype.dispose = function () {
  61808. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  61809. if (this._connectedAnalyser) {
  61810. this._connectedAnalyser.stopDebugCanvas();
  61811. }
  61812. while (this.soundCollection.length) {
  61813. this.soundCollection[0].dispose();
  61814. }
  61815. if (this._outputAudioNode) {
  61816. this._outputAudioNode.disconnect();
  61817. }
  61818. this._outputAudioNode = null;
  61819. }
  61820. };
  61821. SoundTrack.prototype.AddSound = function (sound) {
  61822. if (!this._isInitialized) {
  61823. this._initializeSoundTrackAudioGraph();
  61824. }
  61825. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61826. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  61827. }
  61828. if (sound.soundTrackId) {
  61829. if (sound.soundTrackId === -1) {
  61830. this._scene.mainSoundTrack.RemoveSound(sound);
  61831. }
  61832. else {
  61833. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  61834. }
  61835. }
  61836. this.soundCollection.push(sound);
  61837. sound.soundTrackId = this.id;
  61838. };
  61839. SoundTrack.prototype.RemoveSound = function (sound) {
  61840. var index = this.soundCollection.indexOf(sound);
  61841. if (index !== -1) {
  61842. this.soundCollection.splice(index, 1);
  61843. }
  61844. };
  61845. SoundTrack.prototype.setVolume = function (newVolume) {
  61846. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61847. this._outputAudioNode.gain.value = newVolume;
  61848. }
  61849. };
  61850. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  61851. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61852. for (var i = 0; i < this.soundCollection.length; i++) {
  61853. this.soundCollection[i].switchPanningModelToHRTF();
  61854. }
  61855. }
  61856. };
  61857. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  61858. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61859. for (var i = 0; i < this.soundCollection.length; i++) {
  61860. this.soundCollection[i].switchPanningModelToEqualPower();
  61861. }
  61862. }
  61863. };
  61864. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  61865. if (this._connectedAnalyser) {
  61866. this._connectedAnalyser.stopDebugCanvas();
  61867. }
  61868. this._connectedAnalyser = analyser;
  61869. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61870. this._outputAudioNode.disconnect();
  61871. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  61872. }
  61873. };
  61874. return SoundTrack;
  61875. }());
  61876. BABYLON.SoundTrack = SoundTrack;
  61877. })(BABYLON || (BABYLON = {}));
  61878. //# sourceMappingURL=babylon.soundtrack.js.map
  61879. "use strict";
  61880. var BABYLON;
  61881. (function (BABYLON) {
  61882. var Analyser = /** @class */ (function () {
  61883. function Analyser(scene) {
  61884. this.SMOOTHING = 0.75;
  61885. this.FFT_SIZE = 512;
  61886. this.BARGRAPHAMPLITUDE = 256;
  61887. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  61888. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  61889. this._scene = scene;
  61890. this._audioEngine = BABYLON.Engine.audioEngine;
  61891. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  61892. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  61893. this._webAudioAnalyser.minDecibels = -140;
  61894. this._webAudioAnalyser.maxDecibels = 0;
  61895. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61896. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61897. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  61898. }
  61899. }
  61900. Analyser.prototype.getFrequencyBinCount = function () {
  61901. if (this._audioEngine.canUseWebAudio) {
  61902. return this._webAudioAnalyser.frequencyBinCount;
  61903. }
  61904. else {
  61905. return 0;
  61906. }
  61907. };
  61908. Analyser.prototype.getByteFrequencyData = function () {
  61909. if (this._audioEngine.canUseWebAudio) {
  61910. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61911. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61912. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  61913. }
  61914. return this._byteFreqs;
  61915. };
  61916. Analyser.prototype.getByteTimeDomainData = function () {
  61917. if (this._audioEngine.canUseWebAudio) {
  61918. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61919. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61920. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  61921. }
  61922. return this._byteTime;
  61923. };
  61924. Analyser.prototype.getFloatFrequencyData = function () {
  61925. if (this._audioEngine.canUseWebAudio) {
  61926. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61927. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61928. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  61929. }
  61930. return this._floatFreqs;
  61931. };
  61932. Analyser.prototype.drawDebugCanvas = function () {
  61933. var _this = this;
  61934. if (this._audioEngine.canUseWebAudio) {
  61935. if (!this._debugCanvas) {
  61936. this._debugCanvas = document.createElement("canvas");
  61937. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  61938. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  61939. this._debugCanvas.style.position = "absolute";
  61940. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  61941. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  61942. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  61943. document.body.appendChild(this._debugCanvas);
  61944. this._registerFunc = function () {
  61945. _this.drawDebugCanvas();
  61946. };
  61947. this._scene.registerBeforeRender(this._registerFunc);
  61948. }
  61949. if (this._registerFunc && this._debugCanvasContext) {
  61950. var workingArray = this.getByteFrequencyData();
  61951. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  61952. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  61953. // Draw the frequency domain chart.
  61954. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61955. var value = workingArray[i];
  61956. var percent = value / this.BARGRAPHAMPLITUDE;
  61957. var height = this.DEBUGCANVASSIZE.height * percent;
  61958. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61959. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61960. var hue = i / this.getFrequencyBinCount() * 360;
  61961. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61962. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61963. }
  61964. }
  61965. }
  61966. };
  61967. Analyser.prototype.stopDebugCanvas = function () {
  61968. if (this._debugCanvas) {
  61969. if (this._registerFunc) {
  61970. this._scene.unregisterBeforeRender(this._registerFunc);
  61971. this._registerFunc = null;
  61972. }
  61973. document.body.removeChild(this._debugCanvas);
  61974. this._debugCanvas = null;
  61975. this._debugCanvasContext = null;
  61976. }
  61977. };
  61978. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61979. if (this._audioEngine.canUseWebAudio) {
  61980. inputAudioNode.connect(this._webAudioAnalyser);
  61981. this._webAudioAnalyser.connect(outputAudioNode);
  61982. }
  61983. };
  61984. Analyser.prototype.dispose = function () {
  61985. if (this._audioEngine.canUseWebAudio) {
  61986. this._webAudioAnalyser.disconnect();
  61987. }
  61988. };
  61989. return Analyser;
  61990. }());
  61991. BABYLON.Analyser = Analyser;
  61992. })(BABYLON || (BABYLON = {}));
  61993. //# sourceMappingURL=babylon.analyser.js.map
  61994. "use strict";
  61995. var BABYLON;
  61996. (function (BABYLON) {
  61997. var CubeTexture = /** @class */ (function (_super) {
  61998. __extends(CubeTexture, _super);
  61999. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62000. if (extensions === void 0) { extensions = null; }
  62001. if (noMipmap === void 0) { noMipmap = false; }
  62002. if (files === void 0) { files = null; }
  62003. if (onLoad === void 0) { onLoad = null; }
  62004. if (onError === void 0) { onError = null; }
  62005. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62006. if (prefiltered === void 0) { prefiltered = false; }
  62007. if (forcedExtension === void 0) { forcedExtension = null; }
  62008. var _this = _super.call(this, scene) || this;
  62009. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62010. /**
  62011. * Gets or sets the center of the bounding box associated with the cube texture
  62012. * It must define where the camera used to render the texture was set
  62013. */
  62014. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62015. _this._rotationY = 0;
  62016. _this.name = rootUrl;
  62017. _this.url = rootUrl;
  62018. _this._noMipmap = noMipmap;
  62019. _this.hasAlpha = false;
  62020. _this._format = format;
  62021. _this._prefiltered = prefiltered;
  62022. _this.isCube = true;
  62023. _this._textureMatrix = BABYLON.Matrix.Identity();
  62024. if (prefiltered) {
  62025. _this.gammaSpace = false;
  62026. }
  62027. if (!rootUrl && !files) {
  62028. return _this;
  62029. }
  62030. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62031. var lastDot = rootUrl.lastIndexOf(".");
  62032. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62033. var isDDS = (extension === ".dds");
  62034. if (!files) {
  62035. if (!isDDS && !extensions) {
  62036. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62037. }
  62038. files = [];
  62039. if (extensions) {
  62040. for (var index = 0; index < extensions.length; index++) {
  62041. files.push(rootUrl + extensions[index]);
  62042. }
  62043. }
  62044. }
  62045. _this._files = files;
  62046. if (!_this._texture) {
  62047. if (!scene.useDelayedTextureLoading) {
  62048. if (prefiltered) {
  62049. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62050. }
  62051. else {
  62052. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62053. }
  62054. }
  62055. else {
  62056. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62057. }
  62058. }
  62059. else if (onLoad) {
  62060. if (_this._texture.isReady) {
  62061. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62062. }
  62063. else {
  62064. _this._texture.onLoadedObservable.add(onLoad);
  62065. }
  62066. }
  62067. return _this;
  62068. }
  62069. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62070. get: function () {
  62071. return this._boundingBoxSize;
  62072. },
  62073. /**
  62074. * Gets or sets the size of the bounding box associated with the cube texture
  62075. * When defined, the cubemap will switch to local mode
  62076. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62077. * @example https://www.babylonjs-playground.com/#RNASML
  62078. */
  62079. set: function (value) {
  62080. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62081. return;
  62082. }
  62083. this._boundingBoxSize = value;
  62084. var scene = this.getScene();
  62085. if (scene) {
  62086. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62087. }
  62088. },
  62089. enumerable: true,
  62090. configurable: true
  62091. });
  62092. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62093. /**
  62094. * Gets texture matrix rotation angle around Y axis radians.
  62095. */
  62096. get: function () {
  62097. return this._rotationY;
  62098. },
  62099. /**
  62100. * Sets texture matrix rotation angle around Y axis in radians.
  62101. */
  62102. set: function (value) {
  62103. this._rotationY = value;
  62104. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62105. },
  62106. enumerable: true,
  62107. configurable: true
  62108. });
  62109. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62110. var rootUrlKey = "";
  62111. files.forEach(function (url) { return rootUrlKey += url; });
  62112. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62113. };
  62114. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62115. if (forcedExtension === void 0) { forcedExtension = null; }
  62116. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62117. };
  62118. // Methods
  62119. CubeTexture.prototype.delayLoad = function () {
  62120. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62121. return;
  62122. }
  62123. var scene = this.getScene();
  62124. if (!scene) {
  62125. return;
  62126. }
  62127. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62128. this._texture = this._getFromCache(this.url, this._noMipmap);
  62129. if (!this._texture) {
  62130. if (this._prefiltered) {
  62131. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62132. }
  62133. else {
  62134. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62135. }
  62136. }
  62137. };
  62138. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62139. return this._textureMatrix;
  62140. };
  62141. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62142. this._textureMatrix = value;
  62143. };
  62144. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62145. var texture = BABYLON.SerializationHelper.Parse(function () {
  62146. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  62147. }, parsedTexture, scene);
  62148. // Local Cubemaps
  62149. if (parsedTexture.boundingBoxPosition) {
  62150. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62151. }
  62152. if (parsedTexture.boundingBoxSize) {
  62153. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62154. }
  62155. // Animations
  62156. if (parsedTexture.animations) {
  62157. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62158. var parsedAnimation = parsedTexture.animations[animationIndex];
  62159. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62160. }
  62161. }
  62162. return texture;
  62163. };
  62164. CubeTexture.prototype.clone = function () {
  62165. var _this = this;
  62166. return BABYLON.SerializationHelper.Clone(function () {
  62167. var scene = _this.getScene();
  62168. if (!scene) {
  62169. return _this;
  62170. }
  62171. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62172. }, this);
  62173. };
  62174. __decorate([
  62175. BABYLON.serialize("rotationY")
  62176. ], CubeTexture.prototype, "_rotationY", void 0);
  62177. return CubeTexture;
  62178. }(BABYLON.BaseTexture));
  62179. BABYLON.CubeTexture = CubeTexture;
  62180. })(BABYLON || (BABYLON = {}));
  62181. //# sourceMappingURL=babylon.cubeTexture.js.map
  62182. "use strict";
  62183. var BABYLON;
  62184. (function (BABYLON) {
  62185. var RenderTargetTexture = /** @class */ (function (_super) {
  62186. __extends(RenderTargetTexture, _super);
  62187. /**
  62188. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62189. * or used a shadow, depth texture...
  62190. * @param name The friendly name of the texture
  62191. * @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)
  62192. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62193. * @param generateMipMaps True if mip maps need to be generated after render.
  62194. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62195. * @param type The type of the buffer in the RTT (int, half float, float...)
  62196. * @param isCube True if a cube texture needs to be created
  62197. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62198. * @param generateDepthBuffer True to generate a depth buffer
  62199. * @param generateStencilBuffer True to generate a stencil buffer
  62200. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62201. */
  62202. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62203. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62204. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62205. if (isCube === void 0) { isCube = false; }
  62206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62207. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62208. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62209. if (isMulti === void 0) { isMulti = false; }
  62210. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62211. _this.isCube = isCube;
  62212. /**
  62213. * Use this list to define the list of mesh you want to render.
  62214. */
  62215. _this.renderList = new Array();
  62216. _this.renderParticles = true;
  62217. _this.renderSprites = false;
  62218. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62219. _this.ignoreCameraViewport = false;
  62220. // Events
  62221. /**
  62222. * An event triggered when the texture is unbind.
  62223. */
  62224. _this.onBeforeBindObservable = new BABYLON.Observable();
  62225. /**
  62226. * An event triggered when the texture is unbind.
  62227. */
  62228. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62229. /**
  62230. * An event triggered before rendering the texture
  62231. */
  62232. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62233. /**
  62234. * An event triggered after rendering the texture
  62235. */
  62236. _this.onAfterRenderObservable = new BABYLON.Observable();
  62237. /**
  62238. * An event triggered after the texture clear
  62239. */
  62240. _this.onClearObservable = new BABYLON.Observable();
  62241. _this._currentRefreshId = -1;
  62242. _this._refreshRate = 1;
  62243. _this._samples = 1;
  62244. /**
  62245. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62246. * It must define where the camera used to render the texture is set
  62247. */
  62248. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62249. scene = _this.getScene();
  62250. if (!scene) {
  62251. return _this;
  62252. }
  62253. _this._engine = scene.getEngine();
  62254. _this.name = name;
  62255. _this.isRenderTarget = true;
  62256. _this._initialSizeParameter = size;
  62257. _this._processSizeParameter(size);
  62258. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62259. });
  62260. _this._generateMipMaps = generateMipMaps ? true : false;
  62261. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62262. // Rendering groups
  62263. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62264. if (isMulti) {
  62265. return _this;
  62266. }
  62267. _this._renderTargetOptions = {
  62268. generateMipMaps: generateMipMaps,
  62269. type: type,
  62270. samplingMode: samplingMode,
  62271. generateDepthBuffer: generateDepthBuffer,
  62272. generateStencilBuffer: generateStencilBuffer
  62273. };
  62274. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62275. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62276. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62277. }
  62278. if (isCube) {
  62279. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62280. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62281. _this._textureMatrix = BABYLON.Matrix.Identity();
  62282. }
  62283. else {
  62284. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62285. }
  62286. return _this;
  62287. }
  62288. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62289. get: function () {
  62290. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62291. },
  62292. enumerable: true,
  62293. configurable: true
  62294. });
  62295. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62296. get: function () {
  62297. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62298. },
  62299. enumerable: true,
  62300. configurable: true
  62301. });
  62302. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62303. get: function () {
  62304. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62305. },
  62306. enumerable: true,
  62307. configurable: true
  62308. });
  62309. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62310. set: function (callback) {
  62311. if (this._onAfterUnbindObserver) {
  62312. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62313. }
  62314. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62315. },
  62316. enumerable: true,
  62317. configurable: true
  62318. });
  62319. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62320. set: function (callback) {
  62321. if (this._onBeforeRenderObserver) {
  62322. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62323. }
  62324. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62325. },
  62326. enumerable: true,
  62327. configurable: true
  62328. });
  62329. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62330. set: function (callback) {
  62331. if (this._onAfterRenderObserver) {
  62332. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62333. }
  62334. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62335. },
  62336. enumerable: true,
  62337. configurable: true
  62338. });
  62339. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62340. set: function (callback) {
  62341. if (this._onClearObserver) {
  62342. this.onClearObservable.remove(this._onClearObserver);
  62343. }
  62344. this._onClearObserver = this.onClearObservable.add(callback);
  62345. },
  62346. enumerable: true,
  62347. configurable: true
  62348. });
  62349. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62350. get: function () {
  62351. return this._renderTargetOptions;
  62352. },
  62353. enumerable: true,
  62354. configurable: true
  62355. });
  62356. RenderTargetTexture.prototype._onRatioRescale = function () {
  62357. if (this._sizeRatio) {
  62358. this.resize(this._initialSizeParameter);
  62359. }
  62360. };
  62361. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62362. get: function () {
  62363. return this._boundingBoxSize;
  62364. },
  62365. /**
  62366. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62367. * When defined, the cubemap will switch to local mode
  62368. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62369. * @example https://www.babylonjs-playground.com/#RNASML
  62370. */
  62371. set: function (value) {
  62372. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62373. return;
  62374. }
  62375. this._boundingBoxSize = value;
  62376. var scene = this.getScene();
  62377. if (scene) {
  62378. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62379. }
  62380. },
  62381. enumerable: true,
  62382. configurable: true
  62383. });
  62384. /**
  62385. * Creates a depth stencil texture.
  62386. * This is only available in WebGL 2 or with the depth texture extension available.
  62387. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62388. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62389. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62390. */
  62391. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62392. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62393. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62394. if (generateStencil === void 0) { generateStencil = false; }
  62395. if (!this.getScene()) {
  62396. return;
  62397. }
  62398. var engine = this.getScene().getEngine();
  62399. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62400. bilinearFiltering: bilinearFiltering,
  62401. comparisonFunction: comparisonFunction,
  62402. generateStencil: generateStencil,
  62403. isCube: this.isCube
  62404. });
  62405. engine.setFrameBufferDepthStencilTexture(this);
  62406. };
  62407. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62408. if (size.ratio) {
  62409. this._sizeRatio = size.ratio;
  62410. this._size = {
  62411. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62412. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62413. };
  62414. }
  62415. else {
  62416. this._size = size;
  62417. }
  62418. };
  62419. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62420. get: function () {
  62421. return this._samples;
  62422. },
  62423. set: function (value) {
  62424. if (this._samples === value) {
  62425. return;
  62426. }
  62427. var scene = this.getScene();
  62428. if (!scene) {
  62429. return;
  62430. }
  62431. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62432. },
  62433. enumerable: true,
  62434. configurable: true
  62435. });
  62436. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62437. this._currentRefreshId = -1;
  62438. };
  62439. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62440. get: function () {
  62441. return this._refreshRate;
  62442. },
  62443. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62444. set: function (value) {
  62445. this._refreshRate = value;
  62446. this.resetRefreshCounter();
  62447. },
  62448. enumerable: true,
  62449. configurable: true
  62450. });
  62451. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62452. if (!this._postProcessManager) {
  62453. var scene = this.getScene();
  62454. if (!scene) {
  62455. return;
  62456. }
  62457. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62458. this._postProcesses = new Array();
  62459. }
  62460. this._postProcesses.push(postProcess);
  62461. this._postProcesses[0].autoClear = false;
  62462. };
  62463. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62464. if (!this._postProcesses) {
  62465. return;
  62466. }
  62467. if (dispose) {
  62468. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62469. var postProcess = _a[_i];
  62470. postProcess.dispose();
  62471. }
  62472. }
  62473. this._postProcesses = [];
  62474. };
  62475. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62476. if (!this._postProcesses) {
  62477. return;
  62478. }
  62479. var index = this._postProcesses.indexOf(postProcess);
  62480. if (index === -1) {
  62481. return;
  62482. }
  62483. this._postProcesses.splice(index, 1);
  62484. if (this._postProcesses.length > 0) {
  62485. this._postProcesses[0].autoClear = false;
  62486. }
  62487. };
  62488. RenderTargetTexture.prototype._shouldRender = function () {
  62489. if (this._currentRefreshId === -1) {
  62490. this._currentRefreshId = 1;
  62491. return true;
  62492. }
  62493. if (this.refreshRate === this._currentRefreshId) {
  62494. this._currentRefreshId = 1;
  62495. return true;
  62496. }
  62497. this._currentRefreshId++;
  62498. return false;
  62499. };
  62500. RenderTargetTexture.prototype.getRenderSize = function () {
  62501. if (this._size.width) {
  62502. return this._size.width;
  62503. }
  62504. return this._size;
  62505. };
  62506. RenderTargetTexture.prototype.getRenderWidth = function () {
  62507. if (this._size.width) {
  62508. return this._size.width;
  62509. }
  62510. return this._size;
  62511. };
  62512. RenderTargetTexture.prototype.getRenderHeight = function () {
  62513. if (this._size.width) {
  62514. return this._size.height;
  62515. }
  62516. return this._size;
  62517. };
  62518. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62519. get: function () {
  62520. return true;
  62521. },
  62522. enumerable: true,
  62523. configurable: true
  62524. });
  62525. RenderTargetTexture.prototype.scale = function (ratio) {
  62526. var newSize = this.getRenderSize() * ratio;
  62527. this.resize(newSize);
  62528. };
  62529. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62530. if (this.isCube) {
  62531. return this._textureMatrix;
  62532. }
  62533. return _super.prototype.getReflectionTextureMatrix.call(this);
  62534. };
  62535. RenderTargetTexture.prototype.resize = function (size) {
  62536. this.releaseInternalTexture();
  62537. var scene = this.getScene();
  62538. if (!scene) {
  62539. return;
  62540. }
  62541. this._processSizeParameter(size);
  62542. if (this.isCube) {
  62543. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62544. }
  62545. else {
  62546. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62547. }
  62548. };
  62549. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62550. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62551. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62552. var scene = this.getScene();
  62553. if (!scene) {
  62554. return;
  62555. }
  62556. var engine = scene.getEngine();
  62557. if (this.useCameraPostProcesses !== undefined) {
  62558. useCameraPostProcess = this.useCameraPostProcesses;
  62559. }
  62560. if (this._waitingRenderList) {
  62561. this.renderList = [];
  62562. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62563. var id = this._waitingRenderList[index];
  62564. var mesh_1 = scene.getMeshByID(id);
  62565. if (mesh_1) {
  62566. this.renderList.push(mesh_1);
  62567. }
  62568. }
  62569. delete this._waitingRenderList;
  62570. }
  62571. // Is predicate defined?
  62572. if (this.renderListPredicate) {
  62573. if (this.renderList) {
  62574. this.renderList.splice(0); // Clear previous renderList
  62575. }
  62576. else {
  62577. this.renderList = [];
  62578. }
  62579. var scene = this.getScene();
  62580. if (!scene) {
  62581. return;
  62582. }
  62583. var sceneMeshes = scene.meshes;
  62584. for (var index = 0; index < sceneMeshes.length; index++) {
  62585. var mesh = sceneMeshes[index];
  62586. if (this.renderListPredicate(mesh)) {
  62587. this.renderList.push(mesh);
  62588. }
  62589. }
  62590. }
  62591. this.onBeforeBindObservable.notifyObservers(this);
  62592. // Set custom projection.
  62593. // Needs to be before binding to prevent changing the aspect ratio.
  62594. var camera;
  62595. if (this.activeCamera) {
  62596. camera = this.activeCamera;
  62597. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62598. if (this.activeCamera !== scene.activeCamera) {
  62599. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62600. }
  62601. }
  62602. else {
  62603. camera = scene.activeCamera;
  62604. if (camera) {
  62605. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62606. }
  62607. }
  62608. // Prepare renderingManager
  62609. this._renderingManager.reset();
  62610. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62611. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62612. var sceneRenderId = scene.getRenderId();
  62613. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62614. var mesh = currentRenderList[meshIndex];
  62615. if (mesh) {
  62616. if (!mesh.isReady(this.refreshRate === 0)) {
  62617. this.resetRefreshCounter();
  62618. continue;
  62619. }
  62620. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62621. var isMasked = void 0;
  62622. if (!this.renderList && camera) {
  62623. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62624. }
  62625. else {
  62626. isMasked = false;
  62627. }
  62628. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62629. mesh._activate(sceneRenderId);
  62630. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62631. var subMesh = mesh.subMeshes[subIndex];
  62632. scene._activeIndices.addCount(subMesh.indexCount, false);
  62633. this._renderingManager.dispatch(subMesh, mesh);
  62634. }
  62635. }
  62636. }
  62637. }
  62638. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62639. var particleSystem = scene.particleSystems[particleIndex];
  62640. var emitter = particleSystem.emitter;
  62641. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62642. continue;
  62643. }
  62644. if (currentRenderList.indexOf(emitter) >= 0) {
  62645. this._renderingManager.dispatchParticles(particleSystem);
  62646. }
  62647. }
  62648. if (this.isCube) {
  62649. for (var face = 0; face < 6; face++) {
  62650. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62651. scene.incrementRenderId();
  62652. scene.resetCachedMaterial();
  62653. }
  62654. }
  62655. else {
  62656. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62657. }
  62658. this.onAfterUnbindObservable.notifyObservers(this);
  62659. if (scene.activeCamera) {
  62660. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62661. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62662. }
  62663. engine.setViewport(scene.activeCamera.viewport);
  62664. }
  62665. scene.resetCachedMaterial();
  62666. };
  62667. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62668. var minimum = 128;
  62669. var x = renderDimension * scale;
  62670. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62671. // Ensure we don't exceed the render dimension (while staying POT)
  62672. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62673. };
  62674. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62675. var _this = this;
  62676. if (!this._texture) {
  62677. return;
  62678. }
  62679. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62680. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62681. });
  62682. };
  62683. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  62684. var scene = this.getScene();
  62685. if (!scene) {
  62686. return;
  62687. }
  62688. var engine = scene.getEngine();
  62689. if (!this._texture) {
  62690. return;
  62691. }
  62692. // Bind
  62693. if (this._postProcessManager) {
  62694. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  62695. }
  62696. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  62697. if (this._texture) {
  62698. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  62699. }
  62700. }
  62701. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  62702. // Clear
  62703. if (this.onClearObservable.hasObservers()) {
  62704. this.onClearObservable.notifyObservers(engine);
  62705. }
  62706. else {
  62707. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  62708. }
  62709. if (!this._doNotChangeAspectRatio) {
  62710. scene.updateTransformMatrix(true);
  62711. }
  62712. // Render
  62713. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  62714. if (this._postProcessManager) {
  62715. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  62716. }
  62717. else if (useCameraPostProcess) {
  62718. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  62719. }
  62720. if (!this._doNotChangeAspectRatio) {
  62721. scene.updateTransformMatrix(true);
  62722. }
  62723. // Dump ?
  62724. if (dumpForDebug) {
  62725. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  62726. }
  62727. // Unbind
  62728. if (!this.isCube || faceIndex === 5) {
  62729. if (this.isCube) {
  62730. if (faceIndex === 5) {
  62731. engine.generateMipMapsForCubemap(this._texture);
  62732. }
  62733. }
  62734. this.unbindFrameBuffer(engine, faceIndex);
  62735. }
  62736. else {
  62737. this.onAfterRenderObservable.notifyObservers(faceIndex);
  62738. }
  62739. };
  62740. /**
  62741. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  62742. * This allowed control for front to back rendering or reversly depending of the special needs.
  62743. *
  62744. * @param renderingGroupId The rendering group id corresponding to its index
  62745. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  62746. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  62747. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  62748. */
  62749. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  62750. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  62751. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  62752. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  62753. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  62754. };
  62755. /**
  62756. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  62757. *
  62758. * @param renderingGroupId The rendering group id corresponding to its index
  62759. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  62760. */
  62761. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  62762. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  62763. };
  62764. RenderTargetTexture.prototype.clone = function () {
  62765. var textureSize = this.getSize();
  62766. 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);
  62767. // Base texture
  62768. newTexture.hasAlpha = this.hasAlpha;
  62769. newTexture.level = this.level;
  62770. // RenderTarget Texture
  62771. newTexture.coordinatesMode = this.coordinatesMode;
  62772. if (this.renderList) {
  62773. newTexture.renderList = this.renderList.slice(0);
  62774. }
  62775. return newTexture;
  62776. };
  62777. RenderTargetTexture.prototype.serialize = function () {
  62778. if (!this.name) {
  62779. return null;
  62780. }
  62781. var serializationObject = _super.prototype.serialize.call(this);
  62782. serializationObject.renderTargetSize = this.getRenderSize();
  62783. serializationObject.renderList = [];
  62784. if (this.renderList) {
  62785. for (var index = 0; index < this.renderList.length; index++) {
  62786. serializationObject.renderList.push(this.renderList[index].id);
  62787. }
  62788. }
  62789. return serializationObject;
  62790. };
  62791. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  62792. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  62793. var objBuffer = this.getInternalTexture();
  62794. var scene = this.getScene();
  62795. if (objBuffer && scene) {
  62796. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  62797. }
  62798. };
  62799. RenderTargetTexture.prototype.dispose = function () {
  62800. if (this._postProcessManager) {
  62801. this._postProcessManager.dispose();
  62802. this._postProcessManager = null;
  62803. }
  62804. this.clearPostProcesses(true);
  62805. if (this._resizeObserver) {
  62806. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  62807. this._resizeObserver = null;
  62808. }
  62809. this.renderList = null;
  62810. // Remove from custom render targets
  62811. var scene = this.getScene();
  62812. if (!scene) {
  62813. return;
  62814. }
  62815. var index = scene.customRenderTargets.indexOf(this);
  62816. if (index >= 0) {
  62817. scene.customRenderTargets.splice(index, 1);
  62818. }
  62819. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  62820. var camera = _a[_i];
  62821. index = camera.customRenderTargets.indexOf(this);
  62822. if (index >= 0) {
  62823. camera.customRenderTargets.splice(index, 1);
  62824. }
  62825. }
  62826. _super.prototype.dispose.call(this);
  62827. };
  62828. RenderTargetTexture.prototype._rebuild = function () {
  62829. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62830. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62831. }
  62832. if (this._postProcessManager) {
  62833. this._postProcessManager._rebuild();
  62834. }
  62835. };
  62836. /**
  62837. * Clear the info related to rendering groups preventing retention point in material dispose.
  62838. */
  62839. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  62840. if (this._renderingManager) {
  62841. this._renderingManager.freeRenderingGroups();
  62842. }
  62843. };
  62844. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  62845. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  62846. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  62847. return RenderTargetTexture;
  62848. }(BABYLON.Texture));
  62849. BABYLON.RenderTargetTexture = RenderTargetTexture;
  62850. })(BABYLON || (BABYLON = {}));
  62851. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  62852. "use strict";
  62853. var BABYLON;
  62854. (function (BABYLON) {
  62855. ;
  62856. var MultiRenderTarget = /** @class */ (function (_super) {
  62857. __extends(MultiRenderTarget, _super);
  62858. function MultiRenderTarget(name, size, count, scene, options) {
  62859. var _this = this;
  62860. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  62861. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  62862. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  62863. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  62864. _this._engine = scene.getEngine();
  62865. if (!_this.isSupported) {
  62866. _this.dispose();
  62867. return;
  62868. }
  62869. var types = [];
  62870. var samplingModes = [];
  62871. for (var i = 0; i < count; i++) {
  62872. if (options && options.types && options.types[i] !== undefined) {
  62873. types.push(options.types[i]);
  62874. }
  62875. else {
  62876. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62877. }
  62878. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  62879. samplingModes.push(options.samplingModes[i]);
  62880. }
  62881. else {
  62882. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62883. }
  62884. }
  62885. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  62886. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  62887. _this._size = size;
  62888. _this._multiRenderTargetOptions = {
  62889. samplingModes: samplingModes,
  62890. generateMipMaps: generateMipMaps,
  62891. generateDepthBuffer: generateDepthBuffer,
  62892. generateStencilBuffer: generateStencilBuffer,
  62893. generateDepthTexture: generateDepthTexture,
  62894. types: types,
  62895. textureCount: count
  62896. };
  62897. _this._createInternalTextures();
  62898. _this._createTextures();
  62899. return _this;
  62900. }
  62901. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  62902. get: function () {
  62903. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  62904. },
  62905. enumerable: true,
  62906. configurable: true
  62907. });
  62908. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  62909. get: function () {
  62910. return this._textures;
  62911. },
  62912. enumerable: true,
  62913. configurable: true
  62914. });
  62915. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  62916. get: function () {
  62917. return this._textures[this._textures.length - 1];
  62918. },
  62919. enumerable: true,
  62920. configurable: true
  62921. });
  62922. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  62923. set: function (wrap) {
  62924. if (this._textures) {
  62925. for (var i = 0; i < this._textures.length; i++) {
  62926. this._textures[i].wrapU = wrap;
  62927. }
  62928. }
  62929. },
  62930. enumerable: true,
  62931. configurable: true
  62932. });
  62933. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  62934. set: function (wrap) {
  62935. if (this._textures) {
  62936. for (var i = 0; i < this._textures.length; i++) {
  62937. this._textures[i].wrapV = wrap;
  62938. }
  62939. }
  62940. },
  62941. enumerable: true,
  62942. configurable: true
  62943. });
  62944. MultiRenderTarget.prototype._rebuild = function () {
  62945. this.releaseInternalTextures();
  62946. this._createInternalTextures();
  62947. for (var i = 0; i < this._internalTextures.length; i++) {
  62948. var texture = this._textures[i];
  62949. texture._texture = this._internalTextures[i];
  62950. }
  62951. // Keeps references to frame buffer and stencil/depth buffer
  62952. this._texture = this._internalTextures[0];
  62953. };
  62954. MultiRenderTarget.prototype._createInternalTextures = function () {
  62955. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  62956. };
  62957. MultiRenderTarget.prototype._createTextures = function () {
  62958. this._textures = [];
  62959. for (var i = 0; i < this._internalTextures.length; i++) {
  62960. var texture = new BABYLON.Texture(null, this.getScene());
  62961. texture._texture = this._internalTextures[i];
  62962. this._textures.push(texture);
  62963. }
  62964. // Keeps references to frame buffer and stencil/depth buffer
  62965. this._texture = this._internalTextures[0];
  62966. };
  62967. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  62968. get: function () {
  62969. return this._samples;
  62970. },
  62971. set: function (value) {
  62972. if (this._samples === value) {
  62973. return;
  62974. }
  62975. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62976. },
  62977. enumerable: true,
  62978. configurable: true
  62979. });
  62980. MultiRenderTarget.prototype.resize = function (size) {
  62981. this.releaseInternalTextures();
  62982. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62983. this._createInternalTextures();
  62984. };
  62985. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62986. var _this = this;
  62987. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62988. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62989. });
  62990. };
  62991. MultiRenderTarget.prototype.dispose = function () {
  62992. this.releaseInternalTextures();
  62993. _super.prototype.dispose.call(this);
  62994. };
  62995. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62996. if (!this._internalTextures) {
  62997. return;
  62998. }
  62999. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63000. if (this._internalTextures[i] !== undefined) {
  63001. this._internalTextures[i].dispose();
  63002. this._internalTextures.splice(i, 1);
  63003. }
  63004. }
  63005. };
  63006. return MultiRenderTarget;
  63007. }(BABYLON.RenderTargetTexture));
  63008. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63009. })(BABYLON || (BABYLON = {}));
  63010. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63011. "use strict";
  63012. var BABYLON;
  63013. (function (BABYLON) {
  63014. var MirrorTexture = /** @class */ (function (_super) {
  63015. __extends(MirrorTexture, _super);
  63016. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63017. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63019. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63020. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63021. _this.scene = scene;
  63022. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63023. _this._transformMatrix = BABYLON.Matrix.Zero();
  63024. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63025. _this._adaptiveBlurKernel = 0;
  63026. _this._blurKernelX = 0;
  63027. _this._blurKernelY = 0;
  63028. _this._blurRatio = 1.0;
  63029. _this.ignoreCameraViewport = true;
  63030. _this._updateGammaSpace();
  63031. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63032. _this._updateGammaSpace;
  63033. });
  63034. _this.onBeforeRenderObservable.add(function () {
  63035. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63036. _this._savedViewMatrix = scene.getViewMatrix();
  63037. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63038. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63039. scene.clipPlane = _this.mirrorPlane;
  63040. scene.getEngine().cullBackFaces = false;
  63041. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63042. });
  63043. _this.onAfterRenderObservable.add(function () {
  63044. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63045. scene.getEngine().cullBackFaces = true;
  63046. scene._mirroredCameraPosition = null;
  63047. delete scene.clipPlane;
  63048. });
  63049. return _this;
  63050. }
  63051. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63052. get: function () {
  63053. return this._blurRatio;
  63054. },
  63055. set: function (value) {
  63056. if (this._blurRatio === value) {
  63057. return;
  63058. }
  63059. this._blurRatio = value;
  63060. this._preparePostProcesses();
  63061. },
  63062. enumerable: true,
  63063. configurable: true
  63064. });
  63065. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63066. set: function (value) {
  63067. this._adaptiveBlurKernel = value;
  63068. this._autoComputeBlurKernel();
  63069. },
  63070. enumerable: true,
  63071. configurable: true
  63072. });
  63073. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63074. set: function (value) {
  63075. this.blurKernelX = value;
  63076. this.blurKernelY = value;
  63077. },
  63078. enumerable: true,
  63079. configurable: true
  63080. });
  63081. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63082. get: function () {
  63083. return this._blurKernelX;
  63084. },
  63085. set: function (value) {
  63086. if (this._blurKernelX === value) {
  63087. return;
  63088. }
  63089. this._blurKernelX = value;
  63090. this._preparePostProcesses();
  63091. },
  63092. enumerable: true,
  63093. configurable: true
  63094. });
  63095. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63096. get: function () {
  63097. return this._blurKernelY;
  63098. },
  63099. set: function (value) {
  63100. if (this._blurKernelY === value) {
  63101. return;
  63102. }
  63103. this._blurKernelY = value;
  63104. this._preparePostProcesses();
  63105. },
  63106. enumerable: true,
  63107. configurable: true
  63108. });
  63109. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63110. var engine = this.getScene().getEngine();
  63111. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63112. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63113. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63114. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63115. };
  63116. MirrorTexture.prototype._onRatioRescale = function () {
  63117. if (this._sizeRatio) {
  63118. this.resize(this._initialSizeParameter);
  63119. if (!this._adaptiveBlurKernel) {
  63120. this._preparePostProcesses();
  63121. }
  63122. }
  63123. if (this._adaptiveBlurKernel) {
  63124. this._autoComputeBlurKernel();
  63125. }
  63126. };
  63127. MirrorTexture.prototype._updateGammaSpace = function () {
  63128. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63129. };
  63130. MirrorTexture.prototype._preparePostProcesses = function () {
  63131. this.clearPostProcesses(true);
  63132. if (this._blurKernelX && this._blurKernelY) {
  63133. var engine = this.getScene().getEngine();
  63134. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63135. 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);
  63136. this._blurX.autoClear = false;
  63137. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63138. this._blurX.inputTexture = this._texture;
  63139. }
  63140. else {
  63141. this._blurX.alwaysForcePOT = true;
  63142. }
  63143. 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);
  63144. this._blurY.autoClear = false;
  63145. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63146. this.addPostProcess(this._blurX);
  63147. this.addPostProcess(this._blurY);
  63148. }
  63149. else {
  63150. if (this._blurY) {
  63151. this.removePostProcess(this._blurY);
  63152. this._blurY.dispose();
  63153. this._blurY = null;
  63154. }
  63155. if (this._blurX) {
  63156. this.removePostProcess(this._blurX);
  63157. this._blurX.dispose();
  63158. this._blurX = null;
  63159. }
  63160. }
  63161. };
  63162. MirrorTexture.prototype.clone = function () {
  63163. var scene = this.getScene();
  63164. if (!scene) {
  63165. return this;
  63166. }
  63167. var textureSize = this.getSize();
  63168. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63169. // Base texture
  63170. newTexture.hasAlpha = this.hasAlpha;
  63171. newTexture.level = this.level;
  63172. // Mirror Texture
  63173. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63174. if (this.renderList) {
  63175. newTexture.renderList = this.renderList.slice(0);
  63176. }
  63177. return newTexture;
  63178. };
  63179. MirrorTexture.prototype.serialize = function () {
  63180. if (!this.name) {
  63181. return null;
  63182. }
  63183. var serializationObject = _super.prototype.serialize.call(this);
  63184. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63185. return serializationObject;
  63186. };
  63187. MirrorTexture.prototype.dispose = function () {
  63188. _super.prototype.dispose.call(this);
  63189. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63190. };
  63191. return MirrorTexture;
  63192. }(BABYLON.RenderTargetTexture));
  63193. BABYLON.MirrorTexture = MirrorTexture;
  63194. })(BABYLON || (BABYLON = {}));
  63195. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63196. "use strict";
  63197. var BABYLON;
  63198. (function (BABYLON) {
  63199. /**
  63200. * Creates a refraction texture used by refraction channel of the standard material.
  63201. * @param name the texture name
  63202. * @param size size of the underlying texture
  63203. * @param scene root scene
  63204. */
  63205. var RefractionTexture = /** @class */ (function (_super) {
  63206. __extends(RefractionTexture, _super);
  63207. function RefractionTexture(name, size, scene, generateMipMaps) {
  63208. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63209. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63210. _this.depth = 2.0;
  63211. _this.onBeforeRenderObservable.add(function () {
  63212. scene.clipPlane = _this.refractionPlane;
  63213. });
  63214. _this.onAfterRenderObservable.add(function () {
  63215. delete scene.clipPlane;
  63216. });
  63217. return _this;
  63218. }
  63219. RefractionTexture.prototype.clone = function () {
  63220. var scene = this.getScene();
  63221. if (!scene) {
  63222. return this;
  63223. }
  63224. var textureSize = this.getSize();
  63225. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63226. // Base texture
  63227. newTexture.hasAlpha = this.hasAlpha;
  63228. newTexture.level = this.level;
  63229. // Refraction Texture
  63230. newTexture.refractionPlane = this.refractionPlane.clone();
  63231. if (this.renderList) {
  63232. newTexture.renderList = this.renderList.slice(0);
  63233. }
  63234. newTexture.depth = this.depth;
  63235. return newTexture;
  63236. };
  63237. RefractionTexture.prototype.serialize = function () {
  63238. if (!this.name) {
  63239. return null;
  63240. }
  63241. var serializationObject = _super.prototype.serialize.call(this);
  63242. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63243. serializationObject.depth = this.depth;
  63244. return serializationObject;
  63245. };
  63246. return RefractionTexture;
  63247. }(BABYLON.RenderTargetTexture));
  63248. BABYLON.RefractionTexture = RefractionTexture;
  63249. })(BABYLON || (BABYLON = {}));
  63250. //# sourceMappingURL=babylon.refractionTexture.js.map
  63251. "use strict";
  63252. var BABYLON;
  63253. (function (BABYLON) {
  63254. /**
  63255. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63256. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63257. */
  63258. var DynamicTexture = /** @class */ (function (_super) {
  63259. __extends(DynamicTexture, _super);
  63260. /**
  63261. * Creates a {BABYLON.DynamicTexture}
  63262. * @param name defines the name of the texture
  63263. * @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
  63264. * @param scene defines the scene where you want the texture
  63265. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63266. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63267. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63268. */
  63269. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63270. if (scene === void 0) { scene = null; }
  63271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63272. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63273. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63274. _this.name = name;
  63275. _this._engine = _this.getScene().getEngine();
  63276. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63277. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63278. _this._generateMipMaps = generateMipMaps;
  63279. if (options.getContext) {
  63280. _this._canvas = options;
  63281. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63282. }
  63283. else {
  63284. _this._canvas = document.createElement("canvas");
  63285. if (options.width) {
  63286. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63287. }
  63288. else {
  63289. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63290. }
  63291. }
  63292. var textureSize = _this.getSize();
  63293. _this._canvas.width = textureSize.width;
  63294. _this._canvas.height = textureSize.height;
  63295. _this._context = _this._canvas.getContext("2d");
  63296. return _this;
  63297. }
  63298. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63299. /**
  63300. * Gets the current state of canRescale
  63301. */
  63302. get: function () {
  63303. return true;
  63304. },
  63305. enumerable: true,
  63306. configurable: true
  63307. });
  63308. DynamicTexture.prototype._recreate = function (textureSize) {
  63309. this._canvas.width = textureSize.width;
  63310. this._canvas.height = textureSize.height;
  63311. this.releaseInternalTexture();
  63312. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63313. };
  63314. /**
  63315. * Scales the texture
  63316. * @param ratio the scale factor to apply to both width and height
  63317. */
  63318. DynamicTexture.prototype.scale = function (ratio) {
  63319. var textureSize = this.getSize();
  63320. textureSize.width *= ratio;
  63321. textureSize.height *= ratio;
  63322. this._recreate(textureSize);
  63323. };
  63324. /**
  63325. * Resizes the texture
  63326. * @param width the new width
  63327. * @param height the new height
  63328. */
  63329. DynamicTexture.prototype.scaleTo = function (width, height) {
  63330. var textureSize = this.getSize();
  63331. textureSize.width = width;
  63332. textureSize.height = height;
  63333. this._recreate(textureSize);
  63334. };
  63335. /**
  63336. * Gets the context of the canvas used by the texture
  63337. * @returns the canvas context of the dynamic texture
  63338. */
  63339. DynamicTexture.prototype.getContext = function () {
  63340. return this._context;
  63341. };
  63342. /**
  63343. * Clears the texture
  63344. */
  63345. DynamicTexture.prototype.clear = function () {
  63346. var size = this.getSize();
  63347. this._context.fillRect(0, 0, size.width, size.height);
  63348. };
  63349. /**
  63350. * Updates the texture
  63351. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63352. */
  63353. DynamicTexture.prototype.update = function (invertY) {
  63354. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63355. };
  63356. /**
  63357. * Draws text onto the texture
  63358. * @param text defines the text to be drawn
  63359. * @param x defines the placement of the text from the left
  63360. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63361. * @param font defines the font to be used with font-style, font-size, font-name
  63362. * @param color defines the color used for the text
  63363. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63364. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63365. * @param update defines whether texture is immediately update (default is true)
  63366. */
  63367. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63368. if (update === void 0) { update = true; }
  63369. var size = this.getSize();
  63370. if (clearColor) {
  63371. this._context.fillStyle = clearColor;
  63372. this._context.fillRect(0, 0, size.width, size.height);
  63373. }
  63374. this._context.font = font;
  63375. if (x === null || x === undefined) {
  63376. var textSize = this._context.measureText(text);
  63377. x = (size.width - textSize.width) / 2;
  63378. }
  63379. if (y === null || y === undefined) {
  63380. var fontSize = parseInt((font.replace(/\D/g, '')));
  63381. ;
  63382. y = (size.height / 2) + (fontSize / 3.65);
  63383. }
  63384. this._context.fillStyle = color;
  63385. this._context.fillText(text, x, y);
  63386. if (update) {
  63387. this.update(invertY);
  63388. }
  63389. };
  63390. /**
  63391. * Clones the texture
  63392. * @returns the clone of the texture.
  63393. */
  63394. DynamicTexture.prototype.clone = function () {
  63395. var scene = this.getScene();
  63396. if (!scene) {
  63397. return this;
  63398. }
  63399. var textureSize = this.getSize();
  63400. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63401. // Base texture
  63402. newTexture.hasAlpha = this.hasAlpha;
  63403. newTexture.level = this.level;
  63404. // Dynamic Texture
  63405. newTexture.wrapU = this.wrapU;
  63406. newTexture.wrapV = this.wrapV;
  63407. return newTexture;
  63408. };
  63409. /** @ignore */
  63410. DynamicTexture.prototype._rebuild = function () {
  63411. this.update();
  63412. };
  63413. return DynamicTexture;
  63414. }(BABYLON.Texture));
  63415. BABYLON.DynamicTexture = DynamicTexture;
  63416. })(BABYLON || (BABYLON = {}));
  63417. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63418. "use strict";
  63419. var BABYLON;
  63420. (function (BABYLON) {
  63421. var VideoTexture = /** @class */ (function (_super) {
  63422. __extends(VideoTexture, _super);
  63423. /**
  63424. * Creates a video texture.
  63425. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63426. * @param {string | null} name optional name, will detect from video source, if not defined
  63427. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63428. * @param {BABYLON.Scene} scene is obviously the current scene.
  63429. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63430. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63431. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63432. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63433. */
  63434. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63435. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63436. if (invertY === void 0) { invertY = false; }
  63437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63438. if (settings === void 0) { settings = {
  63439. autoPlay: true,
  63440. loop: true,
  63441. autoUpdateTexture: true,
  63442. }; }
  63443. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63444. _this._createInternalTexture = function () {
  63445. if (_this._texture != null) {
  63446. return;
  63447. }
  63448. if (!_this._engine.needPOTTextures ||
  63449. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63450. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63451. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63452. }
  63453. else {
  63454. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63455. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63456. _this._generateMipMaps = false;
  63457. }
  63458. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63459. _this._texture.isReady = true;
  63460. _this._updateInternalTexture();
  63461. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63462. _this.onLoadObservable.notifyObservers(_this);
  63463. }
  63464. };
  63465. _this.reset = function () {
  63466. if (_this._texture == null) {
  63467. return;
  63468. }
  63469. _this._texture.dispose();
  63470. _this._texture = null;
  63471. };
  63472. _this._updateInternalTexture = function (e) {
  63473. if (_this._texture == null || !_this._texture.isReady) {
  63474. return;
  63475. }
  63476. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63477. return;
  63478. }
  63479. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63480. };
  63481. _this._engine = _this.getScene().getEngine();
  63482. _this._generateMipMaps = generateMipMaps;
  63483. _this._samplingMode = samplingMode;
  63484. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63485. _this.name = name || _this._getName(src);
  63486. _this.video = _this._getVideo(src);
  63487. if (settings.autoPlay !== undefined) {
  63488. _this.video.autoplay = settings.autoPlay;
  63489. }
  63490. if (settings.loop !== undefined) {
  63491. _this.video.loop = settings.loop;
  63492. }
  63493. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63494. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63495. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63496. _this.video.addEventListener("emptied", _this.reset);
  63497. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63498. _this._createInternalTexture();
  63499. }
  63500. return _this;
  63501. }
  63502. VideoTexture.prototype._getName = function (src) {
  63503. if (src instanceof HTMLVideoElement) {
  63504. return src.currentSrc;
  63505. }
  63506. if (typeof src === "object") {
  63507. return src.toString();
  63508. }
  63509. return src;
  63510. };
  63511. ;
  63512. VideoTexture.prototype._getVideo = function (src) {
  63513. if (src instanceof HTMLVideoElement) {
  63514. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63515. return src;
  63516. }
  63517. var video = document.createElement("video");
  63518. if (typeof src === "string") {
  63519. BABYLON.Tools.SetCorsBehavior(src, video);
  63520. video.src = src;
  63521. }
  63522. else {
  63523. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63524. src.forEach(function (url) {
  63525. var source = document.createElement("source");
  63526. source.src = url;
  63527. video.appendChild(source);
  63528. });
  63529. }
  63530. return video;
  63531. };
  63532. ;
  63533. /**
  63534. * Internal method to initiate `update`.
  63535. */
  63536. VideoTexture.prototype._rebuild = function () {
  63537. this.update();
  63538. };
  63539. /**
  63540. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63541. */
  63542. VideoTexture.prototype.update = function () {
  63543. if (!this.autoUpdateTexture) {
  63544. // Expecting user to call `updateTexture` manually
  63545. return;
  63546. }
  63547. this.updateTexture(true);
  63548. };
  63549. /**
  63550. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63551. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63552. */
  63553. VideoTexture.prototype.updateTexture = function (isVisible) {
  63554. if (!isVisible) {
  63555. return;
  63556. }
  63557. if (this.video.paused) {
  63558. return;
  63559. }
  63560. this._updateInternalTexture();
  63561. };
  63562. /**
  63563. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63564. * @param url New url.
  63565. */
  63566. VideoTexture.prototype.updateURL = function (url) {
  63567. this.video.src = url;
  63568. };
  63569. VideoTexture.prototype.dispose = function () {
  63570. _super.prototype.dispose.call(this);
  63571. this.video.removeEventListener("canplay", this._createInternalTexture);
  63572. this.video.removeEventListener("paused", this._updateInternalTexture);
  63573. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63574. this.video.removeEventListener("emptied", this.reset);
  63575. this.video.pause();
  63576. };
  63577. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63578. var video = document.createElement("video");
  63579. var constraintsDeviceId;
  63580. if (constraints && constraints.deviceId) {
  63581. constraintsDeviceId = {
  63582. exact: constraints.deviceId,
  63583. };
  63584. }
  63585. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63586. if (navigator.mediaDevices) {
  63587. navigator.mediaDevices.getUserMedia({ video: constraints })
  63588. .then(function (stream) {
  63589. if (video.mozSrcObject !== undefined) {
  63590. // hack for Firefox < 19
  63591. video.mozSrcObject = stream;
  63592. }
  63593. else {
  63594. video.srcObject = stream;
  63595. }
  63596. var onPlaying = function () {
  63597. if (onReady) {
  63598. onReady(new VideoTexture("video", video, scene, true, true));
  63599. }
  63600. video.removeEventListener("playing", onPlaying);
  63601. };
  63602. video.addEventListener("playing", onPlaying);
  63603. video.play();
  63604. })
  63605. .catch(function (err) {
  63606. BABYLON.Tools.Error(err.name);
  63607. });
  63608. }
  63609. else {
  63610. navigator.getUserMedia =
  63611. navigator.getUserMedia ||
  63612. navigator.webkitGetUserMedia ||
  63613. navigator.mozGetUserMedia ||
  63614. navigator.msGetUserMedia;
  63615. if (navigator.getUserMedia) {
  63616. navigator.getUserMedia({
  63617. video: {
  63618. deviceId: constraintsDeviceId,
  63619. width: {
  63620. min: (constraints && constraints.minWidth) || 256,
  63621. max: (constraints && constraints.maxWidth) || 640,
  63622. },
  63623. height: {
  63624. min: (constraints && constraints.minHeight) || 256,
  63625. max: (constraints && constraints.maxHeight) || 480,
  63626. },
  63627. },
  63628. }, function (stream) {
  63629. if (video.mozSrcObject !== undefined) {
  63630. // hack for Firefox < 19
  63631. video.mozSrcObject = stream;
  63632. }
  63633. else {
  63634. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63635. }
  63636. video.play();
  63637. if (onReady) {
  63638. onReady(new VideoTexture("video", video, scene, true, true));
  63639. }
  63640. }, function (e) {
  63641. BABYLON.Tools.Error(e.name);
  63642. });
  63643. }
  63644. }
  63645. };
  63646. return VideoTexture;
  63647. }(BABYLON.Texture));
  63648. BABYLON.VideoTexture = VideoTexture;
  63649. })(BABYLON || (BABYLON = {}));
  63650. //# sourceMappingURL=babylon.videoTexture.js.map
  63651. "use strict";
  63652. var BABYLON;
  63653. (function (BABYLON) {
  63654. var RawTexture = /** @class */ (function (_super) {
  63655. __extends(RawTexture, _super);
  63656. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63657. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63658. if (invertY === void 0) { invertY = false; }
  63659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63660. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63661. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63662. _this.format = format;
  63663. _this._engine = scene.getEngine();
  63664. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63665. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63666. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63667. return _this;
  63668. }
  63669. RawTexture.prototype.update = function (data) {
  63670. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63671. };
  63672. // Statics
  63673. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63674. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63675. if (invertY === void 0) { invertY = false; }
  63676. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63677. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63678. };
  63679. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63680. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63681. if (invertY === void 0) { invertY = false; }
  63682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63683. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63684. };
  63685. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63686. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63687. if (invertY === void 0) { invertY = false; }
  63688. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63689. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63690. };
  63691. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63692. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63693. if (invertY === void 0) { invertY = false; }
  63694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63695. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63696. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  63697. };
  63698. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63699. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63700. if (invertY === void 0) { invertY = false; }
  63701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63702. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63703. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  63704. };
  63705. return RawTexture;
  63706. }(BABYLON.Texture));
  63707. BABYLON.RawTexture = RawTexture;
  63708. })(BABYLON || (BABYLON = {}));
  63709. //# sourceMappingURL=babylon.rawTexture.js.map
  63710. "use strict";
  63711. var BABYLON;
  63712. (function (BABYLON) {
  63713. /**
  63714. * Class used to store 3D textures containing user data
  63715. */
  63716. var RawTexture3D = /** @class */ (function (_super) {
  63717. __extends(RawTexture3D, _super);
  63718. /**
  63719. * Create a new RawTexture3D
  63720. * @param data defines the data of the texture
  63721. * @param width defines the width of the texture
  63722. * @param height defines the height of the texture
  63723. * @param depth defines the depth of the texture
  63724. * @param format defines the texture format to use
  63725. * @param scene defines the hosting scene
  63726. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  63727. * @param invertY defines if texture must be stored with Y axis inverted
  63728. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  63729. */
  63730. function RawTexture3D(data, width, height, depth,
  63731. /** Gets or sets the texture format to use*/
  63732. format, scene, generateMipMaps, invertY, samplingMode) {
  63733. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63734. if (invertY === void 0) { invertY = false; }
  63735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63736. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63737. _this.format = format;
  63738. _this._engine = scene.getEngine();
  63739. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  63740. _this.is3D = true;
  63741. return _this;
  63742. }
  63743. /**
  63744. * Update the texture with new data
  63745. * @param data defines the data to store in the texture
  63746. */
  63747. RawTexture3D.prototype.update = function (data) {
  63748. if (!this._texture) {
  63749. return;
  63750. }
  63751. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  63752. };
  63753. return RawTexture3D;
  63754. }(BABYLON.Texture));
  63755. BABYLON.RawTexture3D = RawTexture3D;
  63756. })(BABYLON || (BABYLON = {}));
  63757. //# sourceMappingURL=babylon.rawTexture3D.js.map
  63758. "use strict";
  63759. var BABYLON;
  63760. (function (BABYLON) {
  63761. /**
  63762. * PostProcess can be used to apply a shader to a texture after it has been rendered
  63763. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  63764. */
  63765. var PostProcess = /** @class */ (function () {
  63766. /**
  63767. * Creates a new instance PostProcess
  63768. * @param name The name of the PostProcess.
  63769. * @param fragmentUrl The url of the fragment shader to be used.
  63770. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  63771. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  63772. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  63773. * @param camera The camera to apply the render pass to.
  63774. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  63775. * @param engine The engine which the post process will be applied. (default: current engine)
  63776. * @param reusable If the post process can be reused on the same frame. (default: false)
  63777. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  63778. * @param textureType Type of textures used when performing the post process. (default: 0)
  63779. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  63780. * @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
  63781. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  63782. */
  63783. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  63784. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  63785. if (defines === void 0) { defines = null; }
  63786. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63787. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  63788. if (blockCompilation === void 0) { blockCompilation = false; }
  63789. this.name = name;
  63790. /**
  63791. * Width of the texture to apply the post process on
  63792. */
  63793. this.width = -1;
  63794. /**
  63795. * Height of the texture to apply the post process on
  63796. */
  63797. this.height = -1;
  63798. /**
  63799. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  63800. */
  63801. this._outputTexture = null;
  63802. /**
  63803. * If the buffer needs to be cleared before applying the post process. (default: true)
  63804. * Should be set to false if shader will overwrite all previous pixels.
  63805. */
  63806. this.autoClear = true;
  63807. /**
  63808. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  63809. */
  63810. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  63811. /**
  63812. * Animations to be used for the post processing
  63813. */
  63814. this.animations = new Array();
  63815. /**
  63816. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  63817. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  63818. */
  63819. this.enablePixelPerfectMode = false;
  63820. /**
  63821. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  63822. */
  63823. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  63824. /**
  63825. * Force textures to be a power of two (default: false)
  63826. */
  63827. this.alwaysForcePOT = false;
  63828. /**
  63829. * Number of sample textures (default: 1)
  63830. */
  63831. this.samples = 1;
  63832. /**
  63833. * Modify the scale of the post process to be the same as the viewport (default: false)
  63834. */
  63835. this.adaptScaleToCurrentViewport = false;
  63836. this._reusable = false;
  63837. /**
  63838. * Smart array of input and output textures for the post process.
  63839. */
  63840. this._textures = new BABYLON.SmartArray(2);
  63841. /**
  63842. * The index in _textures that corresponds to the output texture.
  63843. */
  63844. this._currentRenderTextureInd = 0;
  63845. this._scaleRatio = new BABYLON.Vector2(1, 1);
  63846. this._texelSize = BABYLON.Vector2.Zero();
  63847. // Events
  63848. /**
  63849. * An event triggered when the postprocess is activated.
  63850. */
  63851. this.onActivateObservable = new BABYLON.Observable();
  63852. /**
  63853. * An event triggered when the postprocess changes its size.
  63854. */
  63855. this.onSizeChangedObservable = new BABYLON.Observable();
  63856. /**
  63857. * An event triggered when the postprocess applies its effect.
  63858. */
  63859. this.onApplyObservable = new BABYLON.Observable();
  63860. /**
  63861. * An event triggered before rendering the postprocess
  63862. */
  63863. this.onBeforeRenderObservable = new BABYLON.Observable();
  63864. /**
  63865. * An event triggered after rendering the postprocess
  63866. */
  63867. this.onAfterRenderObservable = new BABYLON.Observable();
  63868. if (camera != null) {
  63869. this._camera = camera;
  63870. this._scene = camera.getScene();
  63871. camera.attachPostProcess(this);
  63872. this._engine = this._scene.getEngine();
  63873. this._scene.postProcesses.push(this);
  63874. }
  63875. else if (engine) {
  63876. this._engine = engine;
  63877. this._engine.postProcesses.push(this);
  63878. }
  63879. this._options = options;
  63880. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  63881. this._reusable = reusable || false;
  63882. this._textureType = textureType;
  63883. this._samplers = samplers || [];
  63884. this._samplers.push("textureSampler");
  63885. this._fragmentUrl = fragmentUrl;
  63886. this._vertexUrl = vertexUrl;
  63887. this._parameters = parameters || [];
  63888. this._parameters.push("scale");
  63889. this._indexParameters = indexParameters;
  63890. if (!blockCompilation) {
  63891. this.updateEffect(defines);
  63892. }
  63893. }
  63894. Object.defineProperty(PostProcess.prototype, "onActivate", {
  63895. /**
  63896. * A function that is added to the onActivateObservable
  63897. */
  63898. set: function (callback) {
  63899. if (this._onActivateObserver) {
  63900. this.onActivateObservable.remove(this._onActivateObserver);
  63901. }
  63902. if (callback) {
  63903. this._onActivateObserver = this.onActivateObservable.add(callback);
  63904. }
  63905. },
  63906. enumerable: true,
  63907. configurable: true
  63908. });
  63909. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  63910. /**
  63911. * A function that is added to the onSizeChangedObservable
  63912. */
  63913. set: function (callback) {
  63914. if (this._onSizeChangedObserver) {
  63915. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  63916. }
  63917. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  63918. },
  63919. enumerable: true,
  63920. configurable: true
  63921. });
  63922. Object.defineProperty(PostProcess.prototype, "onApply", {
  63923. /**
  63924. * A function that is added to the onApplyObservable
  63925. */
  63926. set: function (callback) {
  63927. if (this._onApplyObserver) {
  63928. this.onApplyObservable.remove(this._onApplyObserver);
  63929. }
  63930. this._onApplyObserver = this.onApplyObservable.add(callback);
  63931. },
  63932. enumerable: true,
  63933. configurable: true
  63934. });
  63935. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  63936. /**
  63937. * A function that is added to the onBeforeRenderObservable
  63938. */
  63939. set: function (callback) {
  63940. if (this._onBeforeRenderObserver) {
  63941. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63942. }
  63943. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63944. },
  63945. enumerable: true,
  63946. configurable: true
  63947. });
  63948. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  63949. /**
  63950. * A function that is added to the onAfterRenderObservable
  63951. */
  63952. set: function (callback) {
  63953. if (this._onAfterRenderObserver) {
  63954. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63955. }
  63956. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63957. },
  63958. enumerable: true,
  63959. configurable: true
  63960. });
  63961. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  63962. /**
  63963. * 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
  63964. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  63965. */
  63966. get: function () {
  63967. return this._textures.data[this._currentRenderTextureInd];
  63968. },
  63969. set: function (value) {
  63970. this._forcedOutputTexture = value;
  63971. },
  63972. enumerable: true,
  63973. configurable: true
  63974. });
  63975. /**
  63976. * Gets the camera which post process is applied to.
  63977. * @returns The camera the post process is applied to.
  63978. */
  63979. PostProcess.prototype.getCamera = function () {
  63980. return this._camera;
  63981. };
  63982. Object.defineProperty(PostProcess.prototype, "texelSize", {
  63983. /**
  63984. * Gets the texel size of the postprocess.
  63985. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  63986. */
  63987. get: function () {
  63988. if (this._shareOutputWithPostProcess) {
  63989. return this._shareOutputWithPostProcess.texelSize;
  63990. }
  63991. if (this._forcedOutputTexture) {
  63992. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  63993. }
  63994. return this._texelSize;
  63995. },
  63996. enumerable: true,
  63997. configurable: true
  63998. });
  63999. /**
  64000. * Gets the engine which this post process belongs to.
  64001. * @returns The engine the post process was enabled with.
  64002. */
  64003. PostProcess.prototype.getEngine = function () {
  64004. return this._engine;
  64005. };
  64006. /**
  64007. * The effect that is created when initializing the post process.
  64008. * @returns The created effect corrisponding the the postprocess.
  64009. */
  64010. PostProcess.prototype.getEffect = function () {
  64011. return this._effect;
  64012. };
  64013. /**
  64014. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64015. * @param postProcess The post process to share the output with.
  64016. * @returns This post process.
  64017. */
  64018. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64019. this._disposeTextures();
  64020. this._shareOutputWithPostProcess = postProcess;
  64021. return this;
  64022. };
  64023. /**
  64024. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64025. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64026. */
  64027. PostProcess.prototype.useOwnOutput = function () {
  64028. if (this._textures.length == 0) {
  64029. this._textures = new BABYLON.SmartArray(2);
  64030. }
  64031. this._shareOutputWithPostProcess = null;
  64032. };
  64033. /**
  64034. * Updates the effect with the current post process compile time values and recompiles the shader.
  64035. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64036. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64037. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64038. * @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
  64039. * @param onCompiled Called when the shader has been compiled.
  64040. * @param onError Called if there is an error when compiling a shader.
  64041. */
  64042. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64043. if (defines === void 0) { defines = null; }
  64044. if (uniforms === void 0) { uniforms = null; }
  64045. if (samplers === void 0) { samplers = null; }
  64046. 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);
  64047. };
  64048. /**
  64049. * The post process is reusable if it can be used multiple times within one frame.
  64050. * @returns If the post process is reusable
  64051. */
  64052. PostProcess.prototype.isReusable = function () {
  64053. return this._reusable;
  64054. };
  64055. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64056. PostProcess.prototype.markTextureDirty = function () {
  64057. this.width = -1;
  64058. };
  64059. /**
  64060. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64061. * 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.
  64062. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64063. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64064. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64065. * @returns The target texture that was bound to be written to.
  64066. */
  64067. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64068. var _this = this;
  64069. if (sourceTexture === void 0) { sourceTexture = null; }
  64070. camera = camera || this._camera;
  64071. var scene = camera.getScene();
  64072. var engine = scene.getEngine();
  64073. var maxSize = engine.getCaps().maxTextureSize;
  64074. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64075. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64076. // 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
  64077. var webVRCamera = camera.parent;
  64078. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64079. requiredWidth /= 2;
  64080. }
  64081. var desiredWidth = (this._options.width || requiredWidth);
  64082. var desiredHeight = this._options.height || requiredHeight;
  64083. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64084. if (this.adaptScaleToCurrentViewport) {
  64085. var currentViewport = engine.currentViewport;
  64086. if (currentViewport) {
  64087. desiredWidth *= currentViewport.width;
  64088. desiredHeight *= currentViewport.height;
  64089. }
  64090. }
  64091. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64092. if (!this._options.width) {
  64093. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64094. }
  64095. if (!this._options.height) {
  64096. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64097. }
  64098. }
  64099. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64100. if (this._textures.length > 0) {
  64101. for (var i = 0; i < this._textures.length; i++) {
  64102. this._engine._releaseTexture(this._textures.data[i]);
  64103. }
  64104. this._textures.reset();
  64105. }
  64106. this.width = desiredWidth;
  64107. this.height = desiredHeight;
  64108. var textureSize = { width: this.width, height: this.height };
  64109. var textureOptions = {
  64110. generateMipMaps: false,
  64111. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64112. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64113. samplingMode: this.renderTargetSamplingMode,
  64114. type: this._textureType
  64115. };
  64116. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64117. if (this._reusable) {
  64118. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64119. }
  64120. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64121. this.onSizeChangedObservable.notifyObservers(this);
  64122. }
  64123. this._textures.forEach(function (texture) {
  64124. if (texture.samples !== _this.samples) {
  64125. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64126. }
  64127. });
  64128. }
  64129. var target;
  64130. if (this._shareOutputWithPostProcess) {
  64131. target = this._shareOutputWithPostProcess.inputTexture;
  64132. }
  64133. else if (this._forcedOutputTexture) {
  64134. target = this._forcedOutputTexture;
  64135. this.width = this._forcedOutputTexture.width;
  64136. this.height = this._forcedOutputTexture.height;
  64137. }
  64138. else {
  64139. target = this.inputTexture;
  64140. }
  64141. // Bind the input of this post process to be used as the output of the previous post process.
  64142. if (this.enablePixelPerfectMode) {
  64143. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64144. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64145. }
  64146. else {
  64147. this._scaleRatio.copyFromFloats(1, 1);
  64148. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64149. }
  64150. this.onActivateObservable.notifyObservers(camera);
  64151. // Clear
  64152. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64153. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64154. }
  64155. if (this._reusable) {
  64156. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64157. }
  64158. return target;
  64159. };
  64160. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64161. /**
  64162. * If the post process is supported.
  64163. */
  64164. get: function () {
  64165. return this._effect.isSupported;
  64166. },
  64167. enumerable: true,
  64168. configurable: true
  64169. });
  64170. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64171. /**
  64172. * The aspect ratio of the output texture.
  64173. */
  64174. get: function () {
  64175. if (this._shareOutputWithPostProcess) {
  64176. return this._shareOutputWithPostProcess.aspectRatio;
  64177. }
  64178. if (this._forcedOutputTexture) {
  64179. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64180. }
  64181. return this.width / this.height;
  64182. },
  64183. enumerable: true,
  64184. configurable: true
  64185. });
  64186. /**
  64187. * Get a value indicating if the post-process is ready to be used
  64188. * @returns true if the post-process is ready (shader is compiled)
  64189. */
  64190. PostProcess.prototype.isReady = function () {
  64191. return this._effect && this._effect.isReady();
  64192. };
  64193. /**
  64194. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64195. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64196. */
  64197. PostProcess.prototype.apply = function () {
  64198. // Check
  64199. if (!this._effect || !this._effect.isReady())
  64200. return null;
  64201. // States
  64202. this._engine.enableEffect(this._effect);
  64203. this._engine.setState(false);
  64204. this._engine.setDepthBuffer(false);
  64205. this._engine.setDepthWrite(false);
  64206. // Alpha
  64207. this._engine.setAlphaMode(this.alphaMode);
  64208. if (this.alphaConstants) {
  64209. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64210. }
  64211. // Bind the output texture of the preivous post process as the input to this post process.
  64212. var source;
  64213. if (this._shareOutputWithPostProcess) {
  64214. source = this._shareOutputWithPostProcess.inputTexture;
  64215. }
  64216. else if (this._forcedOutputTexture) {
  64217. source = this._forcedOutputTexture;
  64218. }
  64219. else {
  64220. source = this.inputTexture;
  64221. }
  64222. this._effect._bindTexture("textureSampler", source);
  64223. // Parameters
  64224. this._effect.setVector2("scale", this._scaleRatio);
  64225. this.onApplyObservable.notifyObservers(this._effect);
  64226. return this._effect;
  64227. };
  64228. PostProcess.prototype._disposeTextures = function () {
  64229. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64230. return;
  64231. }
  64232. if (this._textures.length > 0) {
  64233. for (var i = 0; i < this._textures.length; i++) {
  64234. this._engine._releaseTexture(this._textures.data[i]);
  64235. }
  64236. }
  64237. this._textures.dispose();
  64238. };
  64239. /**
  64240. * Disposes the post process.
  64241. * @param camera The camera to dispose the post process on.
  64242. */
  64243. PostProcess.prototype.dispose = function (camera) {
  64244. camera = camera || this._camera;
  64245. this._disposeTextures();
  64246. if (this._scene) {
  64247. var index_1 = this._scene.postProcesses.indexOf(this);
  64248. if (index_1 !== -1) {
  64249. this._scene.postProcesses.splice(index_1, 1);
  64250. }
  64251. }
  64252. else {
  64253. var index_2 = this._engine.postProcesses.indexOf(this);
  64254. if (index_2 !== -1) {
  64255. this._engine.postProcesses.splice(index_2, 1);
  64256. }
  64257. }
  64258. if (!camera) {
  64259. return;
  64260. }
  64261. camera.detachPostProcess(this);
  64262. var index = camera._postProcesses.indexOf(this);
  64263. if (index === 0 && camera._postProcesses.length > 0) {
  64264. var firstPostProcess = this._camera._getFirstPostProcess();
  64265. if (firstPostProcess) {
  64266. firstPostProcess.markTextureDirty();
  64267. }
  64268. }
  64269. this.onActivateObservable.clear();
  64270. this.onAfterRenderObservable.clear();
  64271. this.onApplyObservable.clear();
  64272. this.onBeforeRenderObservable.clear();
  64273. this.onSizeChangedObservable.clear();
  64274. };
  64275. return PostProcess;
  64276. }());
  64277. BABYLON.PostProcess = PostProcess;
  64278. })(BABYLON || (BABYLON = {}));
  64279. //# sourceMappingURL=babylon.postProcess.js.map
  64280. "use strict";
  64281. var BABYLON;
  64282. (function (BABYLON) {
  64283. var PassPostProcess = /** @class */ (function (_super) {
  64284. __extends(PassPostProcess, _super);
  64285. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64286. if (camera === void 0) { camera = null; }
  64287. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64288. if (blockCompilation === void 0) { blockCompilation = false; }
  64289. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64290. }
  64291. return PassPostProcess;
  64292. }(BABYLON.PostProcess));
  64293. BABYLON.PassPostProcess = PassPostProcess;
  64294. })(BABYLON || (BABYLON = {}));
  64295. //# sourceMappingURL=babylon.passPostProcess.js.map
  64296. "use strict";
  64297. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64298. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64299. s = arguments[i];
  64300. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64301. t[p] = s[p];
  64302. }
  64303. return t;
  64304. };
  64305. var BABYLON;
  64306. (function (BABYLON) {
  64307. /**
  64308. * Default implementation IShadowGenerator.
  64309. * This is the main object responsible of generating shadows in the framework.
  64310. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64311. */
  64312. var ShadowGenerator = /** @class */ (function () {
  64313. /**
  64314. * Creates a ShadowGenerator object.
  64315. * A ShadowGenerator is the required tool to use the shadows.
  64316. * Each light casting shadows needs to use its own ShadowGenerator.
  64317. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64318. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64319. * @param light The light object generating the shadows.
  64320. * @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.
  64321. */
  64322. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64323. this._bias = 0.00005;
  64324. this._normalBias = 0;
  64325. this._blurBoxOffset = 1;
  64326. this._blurScale = 2;
  64327. this._blurKernel = 1;
  64328. this._useKernelBlur = false;
  64329. this._filter = ShadowGenerator.FILTER_NONE;
  64330. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64331. this._contactHardeningLightSizeUVRatio = 0.1;
  64332. this._darkness = 0;
  64333. this._transparencyShadow = false;
  64334. /**
  64335. * Controls the extent to which the shadows fade out at the edge of the frustum
  64336. * Used only by directionals and spots
  64337. */
  64338. this.frustumEdgeFalloff = 0;
  64339. /**
  64340. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64341. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64342. * It might on the other hand introduce peter panning.
  64343. */
  64344. this.forceBackFacesOnly = false;
  64345. this._lightDirection = BABYLON.Vector3.Zero();
  64346. this._viewMatrix = BABYLON.Matrix.Zero();
  64347. this._projectionMatrix = BABYLON.Matrix.Zero();
  64348. this._transformMatrix = BABYLON.Matrix.Zero();
  64349. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64350. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64351. this._currentFaceIndex = 0;
  64352. this._currentFaceIndexCache = 0;
  64353. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64354. this._mapSize = mapSize;
  64355. this._light = light;
  64356. this._scene = light.getScene();
  64357. light._shadowGenerator = this;
  64358. // Texture type fallback from float to int if not supported.
  64359. var caps = this._scene.getEngine().getCaps();
  64360. if (!useFullFloatFirst) {
  64361. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64362. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64363. }
  64364. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64365. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64366. }
  64367. else {
  64368. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64369. }
  64370. }
  64371. else {
  64372. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64373. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64374. }
  64375. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64376. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64377. }
  64378. else {
  64379. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64380. }
  64381. }
  64382. this._initializeGenerator();
  64383. this._applyFilterValues();
  64384. }
  64385. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64386. /**
  64387. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64388. */
  64389. get: function () {
  64390. return this._bias;
  64391. },
  64392. /**
  64393. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64394. */
  64395. set: function (bias) {
  64396. this._bias = bias;
  64397. },
  64398. enumerable: true,
  64399. configurable: true
  64400. });
  64401. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64402. /**
  64403. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64404. */
  64405. get: function () {
  64406. return this._normalBias;
  64407. },
  64408. /**
  64409. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64410. */
  64411. set: function (normalBias) {
  64412. this._normalBias = normalBias;
  64413. },
  64414. enumerable: true,
  64415. configurable: true
  64416. });
  64417. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64418. /**
  64419. * Gets the blur box offset: offset applied during the blur pass.
  64420. * Only usefull if useKernelBlur = false
  64421. */
  64422. get: function () {
  64423. return this._blurBoxOffset;
  64424. },
  64425. /**
  64426. * Sets the blur box offset: offset applied during the blur pass.
  64427. * Only usefull if useKernelBlur = false
  64428. */
  64429. set: function (value) {
  64430. if (this._blurBoxOffset === value) {
  64431. return;
  64432. }
  64433. this._blurBoxOffset = value;
  64434. this._disposeBlurPostProcesses();
  64435. },
  64436. enumerable: true,
  64437. configurable: true
  64438. });
  64439. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64440. /**
  64441. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64442. * 2 means half of the size.
  64443. */
  64444. get: function () {
  64445. return this._blurScale;
  64446. },
  64447. /**
  64448. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64449. * 2 means half of the size.
  64450. */
  64451. set: function (value) {
  64452. if (this._blurScale === value) {
  64453. return;
  64454. }
  64455. this._blurScale = value;
  64456. this._disposeBlurPostProcesses();
  64457. },
  64458. enumerable: true,
  64459. configurable: true
  64460. });
  64461. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64462. /**
  64463. * Gets the blur kernel: kernel size of the blur pass.
  64464. * Only usefull if useKernelBlur = true
  64465. */
  64466. get: function () {
  64467. return this._blurKernel;
  64468. },
  64469. /**
  64470. * Sets the blur kernel: kernel size of the blur pass.
  64471. * Only usefull if useKernelBlur = true
  64472. */
  64473. set: function (value) {
  64474. if (this._blurKernel === value) {
  64475. return;
  64476. }
  64477. this._blurKernel = value;
  64478. this._disposeBlurPostProcesses();
  64479. },
  64480. enumerable: true,
  64481. configurable: true
  64482. });
  64483. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64484. /**
  64485. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64486. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64487. */
  64488. get: function () {
  64489. return this._useKernelBlur;
  64490. },
  64491. /**
  64492. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64493. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64494. */
  64495. set: function (value) {
  64496. if (this._useKernelBlur === value) {
  64497. return;
  64498. }
  64499. this._useKernelBlur = value;
  64500. this._disposeBlurPostProcesses();
  64501. },
  64502. enumerable: true,
  64503. configurable: true
  64504. });
  64505. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64506. /**
  64507. * Gets the depth scale used in ESM mode.
  64508. */
  64509. get: function () {
  64510. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64511. },
  64512. /**
  64513. * Sets the depth scale used in ESM mode.
  64514. * This can override the scale stored on the light.
  64515. */
  64516. set: function (value) {
  64517. this._depthScale = value;
  64518. },
  64519. enumerable: true,
  64520. configurable: true
  64521. });
  64522. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64523. /**
  64524. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64525. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64526. */
  64527. get: function () {
  64528. return this._filter;
  64529. },
  64530. /**
  64531. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64532. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64533. */
  64534. set: function (value) {
  64535. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64536. if (this._light.needCube()) {
  64537. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64538. this.useExponentialShadowMap = true;
  64539. return;
  64540. }
  64541. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64542. this.useCloseExponentialShadowMap = true;
  64543. return;
  64544. }
  64545. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64546. this.usePoissonSampling = true;
  64547. return;
  64548. }
  64549. }
  64550. // Weblg1 fallback for PCF.
  64551. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64552. if (this._scene.getEngine().webGLVersion === 1) {
  64553. this.usePoissonSampling = true;
  64554. return;
  64555. }
  64556. }
  64557. if (this._filter === value) {
  64558. return;
  64559. }
  64560. this._filter = value;
  64561. this._disposeBlurPostProcesses();
  64562. this._applyFilterValues();
  64563. this._light._markMeshesAsLightDirty();
  64564. },
  64565. enumerable: true,
  64566. configurable: true
  64567. });
  64568. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64569. /**
  64570. * Gets if the current filter is set to Poisson Sampling.
  64571. */
  64572. get: function () {
  64573. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64574. },
  64575. /**
  64576. * Sets the current filter to Poisson Sampling.
  64577. */
  64578. set: function (value) {
  64579. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64580. return;
  64581. }
  64582. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64583. },
  64584. enumerable: true,
  64585. configurable: true
  64586. });
  64587. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64588. /**
  64589. * Gets if the current filter is set to VSM.
  64590. * DEPRECATED. Should use useExponentialShadowMap instead.
  64591. */
  64592. get: function () {
  64593. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64594. return this.useExponentialShadowMap;
  64595. },
  64596. /**
  64597. * Sets the current filter is to VSM.
  64598. * DEPRECATED. Should use useExponentialShadowMap instead.
  64599. */
  64600. set: function (value) {
  64601. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64602. this.useExponentialShadowMap = value;
  64603. },
  64604. enumerable: true,
  64605. configurable: true
  64606. });
  64607. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  64608. /**
  64609. * Gets if the current filter is set to blurred VSM.
  64610. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64611. */
  64612. get: function () {
  64613. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64614. return this.useBlurExponentialShadowMap;
  64615. },
  64616. /**
  64617. * Sets the current filter is to blurred VSM.
  64618. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64619. */
  64620. set: function (value) {
  64621. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64622. this.useBlurExponentialShadowMap = value;
  64623. },
  64624. enumerable: true,
  64625. configurable: true
  64626. });
  64627. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  64628. /**
  64629. * Gets if the current filter is set to ESM.
  64630. */
  64631. get: function () {
  64632. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  64633. },
  64634. /**
  64635. * Sets the current filter is to ESM.
  64636. */
  64637. set: function (value) {
  64638. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  64639. return;
  64640. }
  64641. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64642. },
  64643. enumerable: true,
  64644. configurable: true
  64645. });
  64646. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  64647. /**
  64648. * Gets if the current filter is set to filtered ESM.
  64649. */
  64650. get: function () {
  64651. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  64652. },
  64653. /**
  64654. * Gets if the current filter is set to filtered ESM.
  64655. */
  64656. set: function (value) {
  64657. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64658. return;
  64659. }
  64660. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64661. },
  64662. enumerable: true,
  64663. configurable: true
  64664. });
  64665. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  64666. /**
  64667. * Gets if the current filter is set to "close ESM" (using the inverse of the
  64668. * exponential to prevent steep falloff artifacts).
  64669. */
  64670. get: function () {
  64671. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  64672. },
  64673. /**
  64674. * Sets the current filter to "close ESM" (using the inverse of the
  64675. * exponential to prevent steep falloff artifacts).
  64676. */
  64677. set: function (value) {
  64678. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  64679. return;
  64680. }
  64681. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64682. },
  64683. enumerable: true,
  64684. configurable: true
  64685. });
  64686. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  64687. /**
  64688. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  64689. * exponential to prevent steep falloff artifacts).
  64690. */
  64691. get: function () {
  64692. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  64693. },
  64694. /**
  64695. * Sets the current filter to filtered "close ESM" (using the inverse of the
  64696. * exponential to prevent steep falloff artifacts).
  64697. */
  64698. set: function (value) {
  64699. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64700. return;
  64701. }
  64702. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64703. },
  64704. enumerable: true,
  64705. configurable: true
  64706. });
  64707. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  64708. /**
  64709. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  64710. */
  64711. get: function () {
  64712. return this.filter === ShadowGenerator.FILTER_PCF;
  64713. },
  64714. /**
  64715. * Sets the current filter to "PCF" (percentage closer filtering).
  64716. */
  64717. set: function (value) {
  64718. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  64719. return;
  64720. }
  64721. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  64722. },
  64723. enumerable: true,
  64724. configurable: true
  64725. });
  64726. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  64727. /**
  64728. * Gets the PCF or PCSS Quality.
  64729. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64730. */
  64731. get: function () {
  64732. return this._filteringQuality;
  64733. },
  64734. /**
  64735. * Sets the PCF or PCSS Quality.
  64736. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64737. */
  64738. set: function (filteringQuality) {
  64739. this._filteringQuality = filteringQuality;
  64740. },
  64741. enumerable: true,
  64742. configurable: true
  64743. });
  64744. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  64745. /**
  64746. * Gets if the current filter is set to "PCSS" (contact hardening).
  64747. */
  64748. get: function () {
  64749. return this.filter === ShadowGenerator.FILTER_PCSS;
  64750. },
  64751. /**
  64752. * Sets the current filter to "PCSS" (contact hardening).
  64753. */
  64754. set: function (value) {
  64755. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  64756. return;
  64757. }
  64758. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  64759. },
  64760. enumerable: true,
  64761. configurable: true
  64762. });
  64763. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  64764. /**
  64765. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64766. * Using a ratio helps keeping shape stability independently of the map size.
  64767. *
  64768. * It does not account for the light projection as it was having too much
  64769. * instability during the light setup or during light position changes.
  64770. *
  64771. * Only valid if useContactHardeningShadow is true.
  64772. */
  64773. get: function () {
  64774. return this._contactHardeningLightSizeUVRatio;
  64775. },
  64776. /**
  64777. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64778. * Using a ratio helps keeping shape stability independently of the map size.
  64779. *
  64780. * It does not account for the light projection as it was having too much
  64781. * instability during the light setup or during light position changes.
  64782. *
  64783. * Only valid if useContactHardeningShadow is true.
  64784. */
  64785. set: function (contactHardeningLightSizeUVRatio) {
  64786. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  64787. },
  64788. enumerable: true,
  64789. configurable: true
  64790. });
  64791. /**
  64792. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  64793. * 0 means strongest and 1 would means no shadow.
  64794. * @returns the darkness.
  64795. */
  64796. ShadowGenerator.prototype.getDarkness = function () {
  64797. return this._darkness;
  64798. };
  64799. /**
  64800. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  64801. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  64802. * @returns the shadow generator allowing fluent coding.
  64803. */
  64804. ShadowGenerator.prototype.setDarkness = function (darkness) {
  64805. if (darkness >= 1.0)
  64806. this._darkness = 1.0;
  64807. else if (darkness <= 0.0)
  64808. this._darkness = 0.0;
  64809. else
  64810. this._darkness = darkness;
  64811. return this;
  64812. };
  64813. /**
  64814. * Sets the ability to have transparent shadow (boolean).
  64815. * @param transparent True if transparent else False
  64816. * @returns the shadow generator allowing fluent coding
  64817. */
  64818. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  64819. this._transparencyShadow = transparent;
  64820. return this;
  64821. };
  64822. /**
  64823. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  64824. * @returns The render target texture if present otherwise, null
  64825. */
  64826. ShadowGenerator.prototype.getShadowMap = function () {
  64827. return this._shadowMap;
  64828. };
  64829. /**
  64830. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  64831. * @returns The render target texture if the shadow map is present otherwise, null
  64832. */
  64833. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  64834. if (this._shadowMap2) {
  64835. return this._shadowMap2;
  64836. }
  64837. return this._shadowMap;
  64838. };
  64839. /**
  64840. * Helper function to add a mesh and its descendants to the list of shadow casters.
  64841. * @param mesh Mesh to add
  64842. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  64843. * @returns the Shadow Generator itself
  64844. */
  64845. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  64846. if (includeDescendants === void 0) { includeDescendants = true; }
  64847. if (!this._shadowMap) {
  64848. return this;
  64849. }
  64850. if (!this._shadowMap.renderList) {
  64851. this._shadowMap.renderList = [];
  64852. }
  64853. this._shadowMap.renderList.push(mesh);
  64854. if (includeDescendants) {
  64855. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  64856. }
  64857. return this;
  64858. var _a;
  64859. };
  64860. /**
  64861. * Helper function to remove a mesh and its descendants from the list of shadow casters
  64862. * @param mesh Mesh to remove
  64863. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  64864. * @returns the Shadow Generator itself
  64865. */
  64866. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  64867. if (includeDescendants === void 0) { includeDescendants = true; }
  64868. if (!this._shadowMap || !this._shadowMap.renderList) {
  64869. return this;
  64870. }
  64871. var index = this._shadowMap.renderList.indexOf(mesh);
  64872. if (index !== -1) {
  64873. this._shadowMap.renderList.splice(index, 1);
  64874. }
  64875. if (includeDescendants) {
  64876. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  64877. var child = _a[_i];
  64878. this.removeShadowCaster(child);
  64879. }
  64880. }
  64881. return this;
  64882. };
  64883. /**
  64884. * Returns the associated light object.
  64885. * @returns the light generating the shadow
  64886. */
  64887. ShadowGenerator.prototype.getLight = function () {
  64888. return this._light;
  64889. };
  64890. ShadowGenerator.prototype._initializeGenerator = function () {
  64891. this._light._markMeshesAsLightDirty();
  64892. this._initializeShadowMap();
  64893. };
  64894. ShadowGenerator.prototype._initializeShadowMap = function () {
  64895. var _this = this;
  64896. // Render target
  64897. var engine = this._scene.getEngine();
  64898. if (engine.webGLVersion > 1) {
  64899. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  64900. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  64901. }
  64902. else {
  64903. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  64904. }
  64905. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64906. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64907. this._shadowMap.anisotropicFilteringLevel = 1;
  64908. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64909. this._shadowMap.renderParticles = false;
  64910. this._shadowMap.ignoreCameraViewport = true;
  64911. // Record Face Index before render.
  64912. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  64913. _this._currentFaceIndex = faceIndex;
  64914. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64915. engine.setColorWrite(false);
  64916. }
  64917. });
  64918. // Custom render function.
  64919. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  64920. // Blur if required afer render.
  64921. this._shadowMap.onAfterUnbindObservable.add(function () {
  64922. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64923. engine.setColorWrite(true);
  64924. }
  64925. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  64926. return;
  64927. }
  64928. var shadowMap = _this.getShadowMapForRendering();
  64929. if (shadowMap) {
  64930. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  64931. }
  64932. });
  64933. // Clear according to the chosen filter.
  64934. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  64935. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64936. this._shadowMap.onClearObservable.add(function (engine) {
  64937. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64938. engine.clear(clearOne, false, true, false);
  64939. }
  64940. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  64941. engine.clear(clearZero, true, true, false);
  64942. }
  64943. else {
  64944. engine.clear(clearOne, true, true, false);
  64945. }
  64946. });
  64947. };
  64948. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  64949. var _this = this;
  64950. var engine = this._scene.getEngine();
  64951. var targetSize = this._mapSize / this.blurScale;
  64952. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  64953. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  64954. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64955. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64956. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64957. }
  64958. if (this.useKernelBlur) {
  64959. 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);
  64960. this._kernelBlurXPostprocess.width = targetSize;
  64961. this._kernelBlurXPostprocess.height = targetSize;
  64962. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  64963. effect.setTexture("textureSampler", _this._shadowMap);
  64964. });
  64965. 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);
  64966. this._kernelBlurXPostprocess.autoClear = false;
  64967. this._kernelBlurYPostprocess.autoClear = false;
  64968. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64969. this._kernelBlurXPostprocess.packedFloat = true;
  64970. this._kernelBlurYPostprocess.packedFloat = true;
  64971. }
  64972. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  64973. }
  64974. else {
  64975. 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);
  64976. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  64977. effect.setFloat2("screenSize", targetSize, targetSize);
  64978. effect.setTexture("textureSampler", _this._shadowMap);
  64979. });
  64980. this._boxBlurPostprocess.autoClear = false;
  64981. this._blurPostProcesses = [this._boxBlurPostprocess];
  64982. }
  64983. };
  64984. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64985. var index;
  64986. var engine = this._scene.getEngine();
  64987. if (depthOnlySubMeshes.length) {
  64988. engine.setColorWrite(false);
  64989. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64990. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  64991. }
  64992. engine.setColorWrite(true);
  64993. }
  64994. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64995. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  64996. }
  64997. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64998. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  64999. }
  65000. if (this._transparencyShadow) {
  65001. for (index = 0; index < transparentSubMeshes.length; index++) {
  65002. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65003. }
  65004. }
  65005. };
  65006. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65007. var _this = this;
  65008. var mesh = subMesh.getRenderingMesh();
  65009. var scene = this._scene;
  65010. var engine = scene.getEngine();
  65011. var material = subMesh.getMaterial();
  65012. if (!material) {
  65013. return;
  65014. }
  65015. // Culling
  65016. engine.setState(material.backFaceCulling);
  65017. // Managing instances
  65018. var batch = mesh._getInstancesRenderList(subMesh._id);
  65019. if (batch.mustReturn) {
  65020. return;
  65021. }
  65022. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65023. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65024. engine.enableEffect(this._effect);
  65025. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65026. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65027. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65028. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65029. this._effect.setVector3("lightData", this._cachedDirection);
  65030. }
  65031. else {
  65032. this._effect.setVector3("lightData", this._cachedPosition);
  65033. }
  65034. if (scene.activeCamera) {
  65035. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65036. }
  65037. // Alpha test
  65038. if (material && material.needAlphaTesting()) {
  65039. var alphaTexture = material.getAlphaTestTexture();
  65040. if (alphaTexture) {
  65041. this._effect.setTexture("diffuseSampler", alphaTexture);
  65042. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65043. }
  65044. }
  65045. // Bones
  65046. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65047. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65048. }
  65049. // Morph targets
  65050. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65051. if (this.forceBackFacesOnly) {
  65052. engine.setState(true, 0, false, true);
  65053. }
  65054. // Draw
  65055. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65056. if (this.forceBackFacesOnly) {
  65057. engine.setState(true, 0, false, false);
  65058. }
  65059. }
  65060. else {
  65061. // Need to reset refresh rate of the shadowMap
  65062. if (this._shadowMap) {
  65063. this._shadowMap.resetRefreshCounter();
  65064. }
  65065. }
  65066. };
  65067. ShadowGenerator.prototype._applyFilterValues = function () {
  65068. if (!this._shadowMap) {
  65069. return;
  65070. }
  65071. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65072. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65073. }
  65074. else {
  65075. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65076. }
  65077. };
  65078. /**
  65079. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65080. * @param onCompiled Callback triggered at the and of the effects compilation
  65081. * @param options Sets of optional options forcing the compilation with different modes
  65082. */
  65083. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65084. var _this = this;
  65085. var localOptions = __assign({ useInstances: false }, options);
  65086. var shadowMap = this.getShadowMap();
  65087. if (!shadowMap) {
  65088. if (onCompiled) {
  65089. onCompiled(this);
  65090. }
  65091. return;
  65092. }
  65093. var renderList = shadowMap.renderList;
  65094. if (!renderList) {
  65095. if (onCompiled) {
  65096. onCompiled(this);
  65097. }
  65098. return;
  65099. }
  65100. var subMeshes = new Array();
  65101. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65102. var mesh = renderList_1[_i];
  65103. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65104. }
  65105. if (subMeshes.length === 0) {
  65106. if (onCompiled) {
  65107. onCompiled(this);
  65108. }
  65109. return;
  65110. }
  65111. var currentIndex = 0;
  65112. var checkReady = function () {
  65113. if (!_this._scene || !_this._scene.getEngine()) {
  65114. return;
  65115. }
  65116. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65117. currentIndex++;
  65118. if (currentIndex >= subMeshes.length) {
  65119. if (onCompiled) {
  65120. onCompiled(_this);
  65121. }
  65122. return;
  65123. }
  65124. }
  65125. setTimeout(checkReady, 16);
  65126. };
  65127. checkReady();
  65128. };
  65129. /**
  65130. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65131. * @param options Sets of optional options forcing the compilation with different modes
  65132. * @returns A promise that resolves when the compilation completes
  65133. */
  65134. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65135. var _this = this;
  65136. return new Promise(function (resolve) {
  65137. _this.forceCompilation(function () {
  65138. resolve();
  65139. }, options);
  65140. });
  65141. };
  65142. /**
  65143. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65144. * @param subMesh The submesh we want to render in the shadow map
  65145. * @param useInstances Defines wether will draw in the map using instances
  65146. * @returns true if ready otherwise, false
  65147. */
  65148. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65149. var defines = [];
  65150. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65151. defines.push("#define FLOAT");
  65152. }
  65153. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65154. defines.push("#define ESM");
  65155. }
  65156. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65157. defines.push("#define DEPTHTEXTURE");
  65158. }
  65159. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65160. var mesh = subMesh.getMesh();
  65161. var material = subMesh.getMaterial();
  65162. // Normal bias.
  65163. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65164. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65165. defines.push("#define NORMAL");
  65166. if (mesh.nonUniformScaling) {
  65167. defines.push("#define NONUNIFORMSCALING");
  65168. }
  65169. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65170. defines.push("#define DIRECTIONINLIGHTDATA");
  65171. }
  65172. }
  65173. // Alpha test
  65174. if (material && material.needAlphaTesting()) {
  65175. var alphaTexture = material.getAlphaTestTexture();
  65176. if (alphaTexture) {
  65177. defines.push("#define ALPHATEST");
  65178. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65179. attribs.push(BABYLON.VertexBuffer.UVKind);
  65180. defines.push("#define UV1");
  65181. }
  65182. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65183. if (alphaTexture.coordinatesIndex === 1) {
  65184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65185. defines.push("#define UV2");
  65186. }
  65187. }
  65188. }
  65189. }
  65190. // Bones
  65191. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65192. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65193. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65194. if (mesh.numBoneInfluencers > 4) {
  65195. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65196. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65197. }
  65198. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65199. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65200. }
  65201. else {
  65202. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65203. }
  65204. // Morph targets
  65205. var manager = mesh.morphTargetManager;
  65206. var morphInfluencers = 0;
  65207. if (manager) {
  65208. if (manager.numInfluencers > 0) {
  65209. defines.push("#define MORPHTARGETS");
  65210. morphInfluencers = manager.numInfluencers;
  65211. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65212. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65213. }
  65214. }
  65215. // Instances
  65216. if (useInstances) {
  65217. defines.push("#define INSTANCES");
  65218. attribs.push("world0");
  65219. attribs.push("world1");
  65220. attribs.push("world2");
  65221. attribs.push("world3");
  65222. }
  65223. // Get correct effect
  65224. var join = defines.join("\n");
  65225. if (this._cachedDefines !== join) {
  65226. this._cachedDefines = join;
  65227. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65228. }
  65229. if (!this._effect.isReady()) {
  65230. return false;
  65231. }
  65232. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65233. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65234. this._initializeBlurRTTAndPostProcesses();
  65235. }
  65236. }
  65237. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65238. return false;
  65239. }
  65240. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65241. return false;
  65242. }
  65243. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65244. return false;
  65245. }
  65246. return true;
  65247. };
  65248. /**
  65249. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65250. * @param defines Defines of the material we want to update
  65251. * @param lightIndex Index of the light in the enabled light list of the material
  65252. */
  65253. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65254. var scene = this._scene;
  65255. var light = this._light;
  65256. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65257. return;
  65258. }
  65259. defines["SHADOW" + lightIndex] = true;
  65260. if (this.useContactHardeningShadow) {
  65261. defines["SHADOWPCSS" + lightIndex] = true;
  65262. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65263. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65264. }
  65265. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65266. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65267. }
  65268. // else default to high.
  65269. }
  65270. if (this.usePercentageCloserFiltering) {
  65271. defines["SHADOWPCF" + lightIndex] = true;
  65272. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65273. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65274. }
  65275. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65276. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65277. }
  65278. // else default to high.
  65279. }
  65280. else if (this.usePoissonSampling) {
  65281. defines["SHADOWPOISSON" + lightIndex] = true;
  65282. }
  65283. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65284. defines["SHADOWESM" + lightIndex] = true;
  65285. }
  65286. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65287. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65288. }
  65289. if (light.needCube()) {
  65290. defines["SHADOWCUBE" + lightIndex] = true;
  65291. }
  65292. };
  65293. /**
  65294. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65295. * defined in the generator but impacting the effect).
  65296. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65297. * @param effect The effect we are binfing the information for
  65298. */
  65299. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65300. var light = this._light;
  65301. var scene = this._scene;
  65302. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65303. return;
  65304. }
  65305. var camera = scene.activeCamera;
  65306. if (!camera) {
  65307. return;
  65308. }
  65309. var shadowMap = this.getShadowMap();
  65310. if (!shadowMap) {
  65311. return;
  65312. }
  65313. if (!light.needCube()) {
  65314. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65315. }
  65316. // Only PCF uses depth stencil texture.
  65317. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65318. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65319. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65320. }
  65321. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65322. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65323. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65324. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65325. }
  65326. else {
  65327. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65328. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65329. }
  65330. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65331. };
  65332. /**
  65333. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65334. * (eq to shadow prjection matrix * light transform matrix)
  65335. * @returns The transform matrix used to create the shadow map
  65336. */
  65337. ShadowGenerator.prototype.getTransformMatrix = function () {
  65338. var scene = this._scene;
  65339. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65340. return this._transformMatrix;
  65341. }
  65342. this._currentRenderID = scene.getRenderId();
  65343. this._currentFaceIndexCache = this._currentFaceIndex;
  65344. var lightPosition = this._light.position;
  65345. if (this._light.computeTransformedInformation()) {
  65346. lightPosition = this._light.transformedPosition;
  65347. }
  65348. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65349. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65350. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65351. }
  65352. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65353. this._cachedPosition.copyFrom(lightPosition);
  65354. this._cachedDirection.copyFrom(this._lightDirection);
  65355. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65356. var shadowMap = this.getShadowMap();
  65357. if (shadowMap) {
  65358. var renderList = shadowMap.renderList;
  65359. if (renderList) {
  65360. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65361. }
  65362. }
  65363. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65364. }
  65365. return this._transformMatrix;
  65366. };
  65367. /**
  65368. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65369. * Cube and 2D textures for instance.
  65370. */
  65371. ShadowGenerator.prototype.recreateShadowMap = function () {
  65372. var shadowMap = this._shadowMap;
  65373. if (!shadowMap) {
  65374. return;
  65375. }
  65376. // Track render list.
  65377. var renderList = shadowMap.renderList;
  65378. // Clean up existing data.
  65379. this._disposeRTTandPostProcesses();
  65380. // Reinitializes.
  65381. this._initializeGenerator();
  65382. // Reaffect the filter to ensure a correct fallback if necessary.
  65383. this.filter = this.filter;
  65384. // Reaffect the filter.
  65385. this._applyFilterValues();
  65386. // Reaffect Render List.
  65387. this._shadowMap.renderList = renderList;
  65388. };
  65389. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65390. if (this._shadowMap2) {
  65391. this._shadowMap2.dispose();
  65392. this._shadowMap2 = null;
  65393. }
  65394. if (this._boxBlurPostprocess) {
  65395. this._boxBlurPostprocess.dispose();
  65396. this._boxBlurPostprocess = null;
  65397. }
  65398. if (this._kernelBlurXPostprocess) {
  65399. this._kernelBlurXPostprocess.dispose();
  65400. this._kernelBlurXPostprocess = null;
  65401. }
  65402. if (this._kernelBlurYPostprocess) {
  65403. this._kernelBlurYPostprocess.dispose();
  65404. this._kernelBlurYPostprocess = null;
  65405. }
  65406. this._blurPostProcesses = [];
  65407. };
  65408. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65409. if (this._shadowMap) {
  65410. this._shadowMap.dispose();
  65411. this._shadowMap = null;
  65412. }
  65413. this._disposeBlurPostProcesses();
  65414. };
  65415. /**
  65416. * Disposes the ShadowGenerator.
  65417. * Returns nothing.
  65418. */
  65419. ShadowGenerator.prototype.dispose = function () {
  65420. this._disposeRTTandPostProcesses();
  65421. if (this._light) {
  65422. this._light._shadowGenerator = null;
  65423. this._light._markMeshesAsLightDirty();
  65424. }
  65425. };
  65426. /**
  65427. * Serializes the shadow generator setup to a json object.
  65428. * @returns The serialized JSON object
  65429. */
  65430. ShadowGenerator.prototype.serialize = function () {
  65431. var serializationObject = {};
  65432. var shadowMap = this.getShadowMap();
  65433. if (!shadowMap) {
  65434. return serializationObject;
  65435. }
  65436. serializationObject.lightId = this._light.id;
  65437. serializationObject.mapSize = shadowMap.getRenderSize();
  65438. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65439. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65440. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65441. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65442. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65443. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65444. serializationObject.depthScale = this.depthScale;
  65445. serializationObject.darkness = this.getDarkness();
  65446. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65447. serializationObject.blurKernel = this.blurKernel;
  65448. serializationObject.blurScale = this.blurScale;
  65449. serializationObject.useKernelBlur = this.useKernelBlur;
  65450. serializationObject.transparencyShadow = this._transparencyShadow;
  65451. serializationObject.bias = this.bias;
  65452. serializationObject.normalBias = this.normalBias;
  65453. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65454. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65455. serializationObject.filteringQuality = this.filteringQuality;
  65456. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65457. serializationObject.renderList = [];
  65458. if (shadowMap.renderList) {
  65459. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65460. var mesh = shadowMap.renderList[meshIndex];
  65461. serializationObject.renderList.push(mesh.id);
  65462. }
  65463. }
  65464. return serializationObject;
  65465. };
  65466. /**
  65467. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65468. * @param parsedShadowGenerator The JSON object to parse
  65469. * @param scene The scene to create the shadow map for
  65470. * @returns The parsed shadow generator
  65471. */
  65472. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65473. //casting to point light, as light is missing the position attr and typescript complains.
  65474. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65475. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65476. var shadowMap = shadowGenerator.getShadowMap();
  65477. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65478. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65479. meshes.forEach(function (mesh) {
  65480. if (!shadowMap) {
  65481. return;
  65482. }
  65483. if (!shadowMap.renderList) {
  65484. shadowMap.renderList = [];
  65485. }
  65486. shadowMap.renderList.push(mesh);
  65487. });
  65488. }
  65489. if (parsedShadowGenerator.usePoissonSampling) {
  65490. shadowGenerator.usePoissonSampling = true;
  65491. }
  65492. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65493. shadowGenerator.useExponentialShadowMap = true;
  65494. }
  65495. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65496. shadowGenerator.useBlurExponentialShadowMap = true;
  65497. }
  65498. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65499. shadowGenerator.useCloseExponentialShadowMap = true;
  65500. }
  65501. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65502. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65503. }
  65504. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65505. shadowGenerator.usePercentageCloserFiltering = true;
  65506. }
  65507. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65508. shadowGenerator.useContactHardeningShadow = true;
  65509. }
  65510. if (parsedShadowGenerator.filteringQuality) {
  65511. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65512. }
  65513. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65514. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65515. }
  65516. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65517. shadowGenerator.useExponentialShadowMap = true;
  65518. }
  65519. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65520. shadowGenerator.useBlurExponentialShadowMap = true;
  65521. }
  65522. if (parsedShadowGenerator.depthScale) {
  65523. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65524. }
  65525. if (parsedShadowGenerator.blurScale) {
  65526. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65527. }
  65528. if (parsedShadowGenerator.blurBoxOffset) {
  65529. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65530. }
  65531. if (parsedShadowGenerator.useKernelBlur) {
  65532. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65533. }
  65534. if (parsedShadowGenerator.blurKernel) {
  65535. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65536. }
  65537. if (parsedShadowGenerator.bias !== undefined) {
  65538. shadowGenerator.bias = parsedShadowGenerator.bias;
  65539. }
  65540. if (parsedShadowGenerator.normalBias !== undefined) {
  65541. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65542. }
  65543. if (parsedShadowGenerator.darkness) {
  65544. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65545. }
  65546. if (parsedShadowGenerator.transparencyShadow) {
  65547. shadowGenerator.setTransparencyShadow(true);
  65548. }
  65549. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65550. return shadowGenerator;
  65551. };
  65552. /**
  65553. * Shadow generator mode None: no filtering applied.
  65554. */
  65555. ShadowGenerator.FILTER_NONE = 0;
  65556. /**
  65557. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65558. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65559. */
  65560. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65561. /**
  65562. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65563. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65564. */
  65565. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65566. /**
  65567. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65568. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65569. */
  65570. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65571. /**
  65572. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65573. * edge artifacts on steep falloff.
  65574. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65575. */
  65576. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65577. /**
  65578. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65579. * edge artifacts on steep falloff.
  65580. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65581. */
  65582. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65583. /**
  65584. * Shadow generator mode PCF: Percentage Closer Filtering
  65585. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65586. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65587. */
  65588. ShadowGenerator.FILTER_PCF = 6;
  65589. /**
  65590. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65591. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65592. * Contact Hardening
  65593. */
  65594. ShadowGenerator.FILTER_PCSS = 7;
  65595. /**
  65596. * Reserved for PCF and PCSS
  65597. * Highest Quality.
  65598. *
  65599. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65600. *
  65601. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65602. */
  65603. ShadowGenerator.QUALITY_HIGH = 0;
  65604. /**
  65605. * Reserved for PCF and PCSS
  65606. * Good tradeoff for quality/perf cross devices
  65607. *
  65608. * Execute PCF on a 3*3 kernel.
  65609. *
  65610. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  65611. */
  65612. ShadowGenerator.QUALITY_MEDIUM = 1;
  65613. /**
  65614. * Reserved for PCF and PCSS
  65615. * The lowest quality but the fastest.
  65616. *
  65617. * Execute PCF on a 1*1 kernel.
  65618. *
  65619. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  65620. */
  65621. ShadowGenerator.QUALITY_LOW = 2;
  65622. return ShadowGenerator;
  65623. }());
  65624. BABYLON.ShadowGenerator = ShadowGenerator;
  65625. })(BABYLON || (BABYLON = {}));
  65626. //# sourceMappingURL=babylon.shadowGenerator.js.map
  65627. "use strict";
  65628. var BABYLON;
  65629. (function (BABYLON) {
  65630. var DefaultLoadingScreen = /** @class */ (function () {
  65631. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  65632. if (_loadingText === void 0) { _loadingText = ""; }
  65633. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  65634. var _this = this;
  65635. this._renderingCanvas = _renderingCanvas;
  65636. this._loadingText = _loadingText;
  65637. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  65638. // Resize
  65639. this._resizeLoadingUI = function () {
  65640. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  65641. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  65642. if (!_this._loadingDiv) {
  65643. return;
  65644. }
  65645. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  65646. _this._loadingDiv.style.left = canvasRect.left + "px";
  65647. _this._loadingDiv.style.top = canvasRect.top + "px";
  65648. _this._loadingDiv.style.width = canvasRect.width + "px";
  65649. _this._loadingDiv.style.height = canvasRect.height + "px";
  65650. };
  65651. }
  65652. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  65653. if (this._loadingDiv) {
  65654. // Do not add a loading screen if there is already one
  65655. return;
  65656. }
  65657. this._loadingDiv = document.createElement("div");
  65658. this._loadingDiv.id = "babylonjsLoadingDiv";
  65659. this._loadingDiv.style.opacity = "0";
  65660. this._loadingDiv.style.transition = "opacity 1.5s ease";
  65661. this._loadingDiv.style.pointerEvents = "none";
  65662. // Loading text
  65663. this._loadingTextDiv = document.createElement("div");
  65664. this._loadingTextDiv.style.position = "absolute";
  65665. this._loadingTextDiv.style.left = "0";
  65666. this._loadingTextDiv.style.top = "50%";
  65667. this._loadingTextDiv.style.marginTop = "80px";
  65668. this._loadingTextDiv.style.width = "100%";
  65669. this._loadingTextDiv.style.height = "20px";
  65670. this._loadingTextDiv.style.fontFamily = "Arial";
  65671. this._loadingTextDiv.style.fontSize = "14px";
  65672. this._loadingTextDiv.style.color = "white";
  65673. this._loadingTextDiv.style.textAlign = "center";
  65674. this._loadingTextDiv.innerHTML = "Loading";
  65675. this._loadingDiv.appendChild(this._loadingTextDiv);
  65676. //set the predefined text
  65677. this._loadingTextDiv.innerHTML = this._loadingText;
  65678. // Generating keyframes
  65679. var style = document.createElement('style');
  65680. style.type = 'text/css';
  65681. 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 }";
  65682. style.innerHTML = keyFrames;
  65683. document.getElementsByTagName('head')[0].appendChild(style);
  65684. // Loading img
  65685. var imgBack = new Image();
  65686. 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";
  65687. imgBack.style.position = "absolute";
  65688. imgBack.style.left = "50%";
  65689. imgBack.style.top = "50%";
  65690. imgBack.style.marginLeft = "-60px";
  65691. imgBack.style.marginTop = "-60px";
  65692. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  65693. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  65694. imgBack.style.transformOrigin = "50% 50%";
  65695. imgBack.style.webkitTransformOrigin = "50% 50%";
  65696. this._loadingDiv.appendChild(imgBack);
  65697. this._resizeLoadingUI();
  65698. window.addEventListener("resize", this._resizeLoadingUI);
  65699. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65700. document.body.appendChild(this._loadingDiv);
  65701. this._loadingDiv.style.opacity = "1";
  65702. };
  65703. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  65704. var _this = this;
  65705. if (!this._loadingDiv) {
  65706. return;
  65707. }
  65708. var onTransitionEnd = function () {
  65709. if (!_this._loadingDiv) {
  65710. return;
  65711. }
  65712. document.body.removeChild(_this._loadingDiv);
  65713. window.removeEventListener("resize", _this._resizeLoadingUI);
  65714. _this._loadingDiv = null;
  65715. };
  65716. this._loadingDiv.style.opacity = "0";
  65717. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  65718. };
  65719. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  65720. set: function (text) {
  65721. this._loadingText = text;
  65722. if (this._loadingTextDiv) {
  65723. this._loadingTextDiv.innerHTML = this._loadingText;
  65724. }
  65725. },
  65726. enumerable: true,
  65727. configurable: true
  65728. });
  65729. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  65730. get: function () {
  65731. return this._loadingDivBackgroundColor;
  65732. },
  65733. set: function (color) {
  65734. this._loadingDivBackgroundColor = color;
  65735. if (!this._loadingDiv) {
  65736. return;
  65737. }
  65738. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65739. },
  65740. enumerable: true,
  65741. configurable: true
  65742. });
  65743. return DefaultLoadingScreen;
  65744. }());
  65745. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  65746. })(BABYLON || (BABYLON = {}));
  65747. //# sourceMappingURL=babylon.loadingScreen.js.map
  65748. "use strict";
  65749. var BABYLON;
  65750. (function (BABYLON) {
  65751. var SceneLoaderProgressEvent = /** @class */ (function () {
  65752. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  65753. this.lengthComputable = lengthComputable;
  65754. this.loaded = loaded;
  65755. this.total = total;
  65756. }
  65757. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  65758. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  65759. };
  65760. return SceneLoaderProgressEvent;
  65761. }());
  65762. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  65763. var SceneLoader = /** @class */ (function () {
  65764. function SceneLoader() {
  65765. }
  65766. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  65767. get: function () {
  65768. return 0;
  65769. },
  65770. enumerable: true,
  65771. configurable: true
  65772. });
  65773. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  65774. get: function () {
  65775. return 1;
  65776. },
  65777. enumerable: true,
  65778. configurable: true
  65779. });
  65780. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  65781. get: function () {
  65782. return 2;
  65783. },
  65784. enumerable: true,
  65785. configurable: true
  65786. });
  65787. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  65788. get: function () {
  65789. return 3;
  65790. },
  65791. enumerable: true,
  65792. configurable: true
  65793. });
  65794. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  65795. get: function () {
  65796. return SceneLoader._ForceFullSceneLoadingForIncremental;
  65797. },
  65798. set: function (value) {
  65799. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  65800. },
  65801. enumerable: true,
  65802. configurable: true
  65803. });
  65804. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  65805. get: function () {
  65806. return SceneLoader._ShowLoadingScreen;
  65807. },
  65808. set: function (value) {
  65809. SceneLoader._ShowLoadingScreen = value;
  65810. },
  65811. enumerable: true,
  65812. configurable: true
  65813. });
  65814. Object.defineProperty(SceneLoader, "loggingLevel", {
  65815. get: function () {
  65816. return SceneLoader._loggingLevel;
  65817. },
  65818. set: function (value) {
  65819. SceneLoader._loggingLevel = value;
  65820. },
  65821. enumerable: true,
  65822. configurable: true
  65823. });
  65824. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  65825. get: function () {
  65826. return SceneLoader._CleanBoneMatrixWeights;
  65827. },
  65828. set: function (value) {
  65829. SceneLoader._CleanBoneMatrixWeights = value;
  65830. },
  65831. enumerable: true,
  65832. configurable: true
  65833. });
  65834. SceneLoader._getDefaultPlugin = function () {
  65835. return SceneLoader._registeredPlugins[".babylon"];
  65836. };
  65837. SceneLoader._getPluginForExtension = function (extension) {
  65838. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  65839. if (registeredPlugin) {
  65840. return registeredPlugin;
  65841. }
  65842. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  65843. return SceneLoader._getDefaultPlugin();
  65844. };
  65845. SceneLoader._getPluginForDirectLoad = function (data) {
  65846. for (var extension in SceneLoader._registeredPlugins) {
  65847. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  65848. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  65849. return SceneLoader._registeredPlugins[extension];
  65850. }
  65851. }
  65852. return SceneLoader._getDefaultPlugin();
  65853. };
  65854. SceneLoader._getPluginForFilename = function (sceneFilename) {
  65855. if (sceneFilename.name) {
  65856. sceneFilename = sceneFilename.name;
  65857. }
  65858. var queryStringPosition = sceneFilename.indexOf("?");
  65859. if (queryStringPosition !== -1) {
  65860. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  65861. }
  65862. var dotPosition = sceneFilename.lastIndexOf(".");
  65863. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  65864. return SceneLoader._getPluginForExtension(extension);
  65865. };
  65866. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  65867. SceneLoader._getDirectLoad = function (sceneFilename) {
  65868. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  65869. return sceneFilename.substr(5);
  65870. }
  65871. return null;
  65872. };
  65873. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  65874. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  65875. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  65876. var plugin;
  65877. if (registeredPlugin.plugin.createPlugin) {
  65878. plugin = registeredPlugin.plugin.createPlugin();
  65879. }
  65880. else {
  65881. plugin = registeredPlugin.plugin;
  65882. }
  65883. var useArrayBuffer = registeredPlugin.isBinary;
  65884. var database;
  65885. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  65886. var dataCallback = function (data, responseURL) {
  65887. if (scene.isDisposed) {
  65888. onError("Scene has been disposed");
  65889. return;
  65890. }
  65891. scene.database = database;
  65892. onSuccess(plugin, data, responseURL);
  65893. };
  65894. var request = null;
  65895. var pluginDisposed = false;
  65896. var onDisposeObservable = plugin.onDisposeObservable;
  65897. if (onDisposeObservable) {
  65898. onDisposeObservable.add(function () {
  65899. pluginDisposed = true;
  65900. if (request) {
  65901. request.abort();
  65902. request = null;
  65903. }
  65904. onDispose();
  65905. });
  65906. }
  65907. var manifestChecked = function () {
  65908. if (pluginDisposed) {
  65909. return;
  65910. }
  65911. var url = rootUrl + sceneFilename;
  65912. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  65913. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  65914. } : undefined, database, useArrayBuffer, function (request, exception) {
  65915. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  65916. });
  65917. };
  65918. if (directLoad) {
  65919. dataCallback(directLoad);
  65920. return plugin;
  65921. }
  65922. if (rootUrl.indexOf("file:") === -1) {
  65923. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  65924. if (canUseOfflineSupport) {
  65925. // Also check for exceptions
  65926. var exceptionFound = false;
  65927. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  65928. var regex = _a[_i];
  65929. if (regex.test(rootUrl + sceneFilename)) {
  65930. exceptionFound = true;
  65931. break;
  65932. }
  65933. }
  65934. canUseOfflineSupport = !exceptionFound;
  65935. }
  65936. if (canUseOfflineSupport) {
  65937. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  65938. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  65939. }
  65940. else {
  65941. manifestChecked();
  65942. }
  65943. }
  65944. else {
  65945. var fileOrString = sceneFilename;
  65946. if (fileOrString.name) {
  65947. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  65948. }
  65949. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  65950. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  65951. }
  65952. else {
  65953. onError("Unable to find file named " + sceneFilename);
  65954. }
  65955. }
  65956. return plugin;
  65957. };
  65958. // Public functions
  65959. SceneLoader.GetPluginForExtension = function (extension) {
  65960. return SceneLoader._getPluginForExtension(extension).plugin;
  65961. };
  65962. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  65963. return !!SceneLoader._registeredPlugins[extension];
  65964. };
  65965. SceneLoader.RegisterPlugin = function (plugin) {
  65966. if (typeof plugin.extensions === "string") {
  65967. var extension = plugin.extensions;
  65968. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65969. plugin: plugin,
  65970. isBinary: false
  65971. };
  65972. }
  65973. else {
  65974. var extensions = plugin.extensions;
  65975. Object.keys(extensions).forEach(function (extension) {
  65976. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65977. plugin: plugin,
  65978. isBinary: extensions[extension].isBinary
  65979. };
  65980. });
  65981. }
  65982. };
  65983. /**
  65984. * Import meshes into a scene
  65985. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65986. * @param rootUrl a string that defines the root url for scene and resources
  65987. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65988. * @param scene the instance of BABYLON.Scene to append to
  65989. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  65990. * @param onProgress a callback with a progress event for each file being loaded
  65991. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65992. * @param pluginExtension the extension used to determine the plugin
  65993. * @returns The loaded plugin
  65994. */
  65995. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65996. if (onSuccess === void 0) { onSuccess = null; }
  65997. if (onProgress === void 0) { onProgress = null; }
  65998. if (onError === void 0) { onError = null; }
  65999. if (pluginExtension === void 0) { pluginExtension = null; }
  66000. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66001. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66002. return null;
  66003. }
  66004. var loadingToken = {};
  66005. scene._addPendingData(loadingToken);
  66006. var disposeHandler = function () {
  66007. scene._removePendingData(loadingToken);
  66008. };
  66009. var errorHandler = function (message, exception) {
  66010. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66011. if (onError) {
  66012. onError(scene, errorMessage, exception);
  66013. }
  66014. else {
  66015. BABYLON.Tools.Error(errorMessage);
  66016. // should the exception be thrown?
  66017. }
  66018. disposeHandler();
  66019. };
  66020. var progressHandler = onProgress ? function (event) {
  66021. try {
  66022. onProgress(event);
  66023. }
  66024. catch (e) {
  66025. errorHandler("Error in onProgress callback", e);
  66026. }
  66027. } : undefined;
  66028. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66029. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66030. if (onSuccess) {
  66031. try {
  66032. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66033. }
  66034. catch (e) {
  66035. errorHandler("Error in onSuccess callback", e);
  66036. }
  66037. }
  66038. scene._removePendingData(loadingToken);
  66039. };
  66040. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66041. if (plugin.rewriteRootURL) {
  66042. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66043. }
  66044. if (sceneFilename === "") {
  66045. if (sceneFilename === "") {
  66046. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66047. }
  66048. }
  66049. if (plugin.importMesh) {
  66050. var syncedPlugin = plugin;
  66051. var meshes = new Array();
  66052. var particleSystems = new Array();
  66053. var skeletons = new Array();
  66054. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66055. return;
  66056. }
  66057. scene.loadingPluginName = plugin.name;
  66058. successHandler(meshes, particleSystems, skeletons, []);
  66059. }
  66060. else {
  66061. var asyncedPlugin = plugin;
  66062. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66063. scene.loadingPluginName = plugin.name;
  66064. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66065. }).catch(function (error) {
  66066. errorHandler(error.message, error);
  66067. });
  66068. }
  66069. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66070. };
  66071. /**
  66072. * Import meshes into a scene
  66073. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66074. * @param rootUrl a string that defines the root url for scene and resources
  66075. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66076. * @param scene the instance of BABYLON.Scene to append to
  66077. * @param onProgress a callback with a progress event for each file being loaded
  66078. * @param pluginExtension the extension used to determine the plugin
  66079. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66080. */
  66081. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66082. if (onProgress === void 0) { onProgress = null; }
  66083. if (pluginExtension === void 0) { pluginExtension = null; }
  66084. return new Promise(function (resolve, reject) {
  66085. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66086. resolve({
  66087. meshes: meshes,
  66088. particleSystems: particleSystems,
  66089. skeletons: skeletons,
  66090. animationGroups: animationGroups
  66091. });
  66092. }, onProgress, function (scene, message, exception) {
  66093. reject(exception || new Error(message));
  66094. });
  66095. });
  66096. };
  66097. /**
  66098. * Load a scene
  66099. * @param rootUrl a string that defines the root url for scene and resources
  66100. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66101. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66102. * @param onSuccess a callback with the scene when import succeeds
  66103. * @param onProgress a callback with a progress event for each file being loaded
  66104. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66105. * @param pluginExtension the extension used to determine the plugin
  66106. * @returns The loaded plugin
  66107. */
  66108. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66109. if (onSuccess === void 0) { onSuccess = null; }
  66110. if (onProgress === void 0) { onProgress = null; }
  66111. if (onError === void 0) { onError = null; }
  66112. if (pluginExtension === void 0) { pluginExtension = null; }
  66113. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66114. };
  66115. /**
  66116. * Load a scene
  66117. * @param rootUrl a string that defines the root url for scene and resources
  66118. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66119. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66120. * @param onProgress a callback with a progress event for each file being loaded
  66121. * @param pluginExtension the extension used to determine the plugin
  66122. * @returns The loaded scene
  66123. */
  66124. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66125. if (onProgress === void 0) { onProgress = null; }
  66126. if (pluginExtension === void 0) { pluginExtension = null; }
  66127. return new Promise(function (resolve, reject) {
  66128. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66129. resolve(scene);
  66130. }, onProgress, function (scene, message, exception) {
  66131. reject(exception || new Error(message));
  66132. }, pluginExtension);
  66133. });
  66134. };
  66135. /**
  66136. * Append a scene
  66137. * @param rootUrl a string that defines the root url for scene and resources
  66138. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66139. * @param scene is the instance of BABYLON.Scene to append to
  66140. * @param onSuccess a callback with the scene when import succeeds
  66141. * @param onProgress a callback with a progress event for each file being loaded
  66142. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66143. * @param pluginExtension the extension used to determine the plugin
  66144. * @returns The loaded plugin
  66145. */
  66146. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66147. if (onSuccess === void 0) { onSuccess = null; }
  66148. if (onProgress === void 0) { onProgress = null; }
  66149. if (onError === void 0) { onError = null; }
  66150. if (pluginExtension === void 0) { pluginExtension = null; }
  66151. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66152. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66153. return null;
  66154. }
  66155. if (SceneLoader.ShowLoadingScreen) {
  66156. scene.getEngine().displayLoadingUI();
  66157. }
  66158. var loadingToken = {};
  66159. scene._addPendingData(loadingToken);
  66160. var disposeHandler = function () {
  66161. scene._removePendingData(loadingToken);
  66162. scene.getEngine().hideLoadingUI();
  66163. };
  66164. var errorHandler = function (message, exception) {
  66165. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66166. if (onError) {
  66167. onError(scene, errorMessage, exception);
  66168. }
  66169. else {
  66170. BABYLON.Tools.Error(errorMessage);
  66171. // should the exception be thrown?
  66172. }
  66173. disposeHandler();
  66174. };
  66175. var progressHandler = onProgress ? function (event) {
  66176. try {
  66177. onProgress(event);
  66178. }
  66179. catch (e) {
  66180. errorHandler("Error in onProgress callback", e);
  66181. }
  66182. } : undefined;
  66183. var successHandler = function () {
  66184. if (onSuccess) {
  66185. try {
  66186. onSuccess(scene);
  66187. }
  66188. catch (e) {
  66189. errorHandler("Error in onSuccess callback", e);
  66190. }
  66191. }
  66192. scene._removePendingData(loadingToken);
  66193. };
  66194. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66195. if (sceneFilename === "") {
  66196. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66197. }
  66198. if (plugin.load) {
  66199. var syncedPlugin = plugin;
  66200. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66201. return;
  66202. }
  66203. scene.loadingPluginName = plugin.name;
  66204. successHandler();
  66205. }
  66206. else {
  66207. var asyncedPlugin = plugin;
  66208. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66209. scene.loadingPluginName = plugin.name;
  66210. successHandler();
  66211. }).catch(function (error) {
  66212. errorHandler(error.message, error);
  66213. });
  66214. }
  66215. if (SceneLoader.ShowLoadingScreen) {
  66216. scene.executeWhenReady(function () {
  66217. scene.getEngine().hideLoadingUI();
  66218. });
  66219. }
  66220. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66221. };
  66222. /**
  66223. * Append a scene
  66224. * @param rootUrl a string that defines the root url for scene and resources
  66225. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66226. * @param scene is the instance of BABYLON.Scene to append to
  66227. * @param onProgress a callback with a progress event for each file being loaded
  66228. * @param pluginExtension the extension used to determine the plugin
  66229. * @returns The given scene
  66230. */
  66231. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66232. if (onProgress === void 0) { onProgress = null; }
  66233. if (pluginExtension === void 0) { pluginExtension = null; }
  66234. return new Promise(function (resolve, reject) {
  66235. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66236. resolve(scene);
  66237. }, onProgress, function (scene, message, exception) {
  66238. reject(exception || new Error(message));
  66239. }, pluginExtension);
  66240. });
  66241. };
  66242. /**
  66243. * Load a scene into an asset container
  66244. * @param rootUrl a string that defines the root url for scene and resources
  66245. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66246. * @param scene is the instance of BABYLON.Scene to append to
  66247. * @param onSuccess a callback with the scene when import succeeds
  66248. * @param onProgress a callback with a progress event for each file being loaded
  66249. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66250. * @param pluginExtension the extension used to determine the plugin
  66251. * @returns The loaded plugin
  66252. */
  66253. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66254. if (onSuccess === void 0) { onSuccess = null; }
  66255. if (onProgress === void 0) { onProgress = null; }
  66256. if (onError === void 0) { onError = null; }
  66257. if (pluginExtension === void 0) { pluginExtension = null; }
  66258. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66259. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66260. return null;
  66261. }
  66262. var loadingToken = {};
  66263. scene._addPendingData(loadingToken);
  66264. var disposeHandler = function () {
  66265. scene._removePendingData(loadingToken);
  66266. };
  66267. var errorHandler = function (message, exception) {
  66268. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66269. if (onError) {
  66270. onError(scene, errorMessage, exception);
  66271. }
  66272. else {
  66273. BABYLON.Tools.Error(errorMessage);
  66274. // should the exception be thrown?
  66275. }
  66276. disposeHandler();
  66277. };
  66278. var progressHandler = onProgress ? function (event) {
  66279. try {
  66280. onProgress(event);
  66281. }
  66282. catch (e) {
  66283. errorHandler("Error in onProgress callback", e);
  66284. }
  66285. } : undefined;
  66286. var successHandler = function (assets) {
  66287. if (onSuccess) {
  66288. try {
  66289. onSuccess(assets);
  66290. }
  66291. catch (e) {
  66292. errorHandler("Error in onSuccess callback", e);
  66293. }
  66294. }
  66295. scene._removePendingData(loadingToken);
  66296. };
  66297. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66298. if (plugin.loadAssetContainer) {
  66299. var syncedPlugin = plugin;
  66300. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66301. if (!assetContainer) {
  66302. return;
  66303. }
  66304. scene.loadingPluginName = plugin.name;
  66305. successHandler(assetContainer);
  66306. }
  66307. else if (plugin.loadAssetContainerAsync) {
  66308. var asyncedPlugin = plugin;
  66309. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66310. scene.loadingPluginName = plugin.name;
  66311. successHandler(assetContainer);
  66312. }).catch(function (error) {
  66313. errorHandler(error.message, error);
  66314. });
  66315. }
  66316. else {
  66317. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66318. }
  66319. if (SceneLoader.ShowLoadingScreen) {
  66320. scene.executeWhenReady(function () {
  66321. scene.getEngine().hideLoadingUI();
  66322. });
  66323. }
  66324. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66325. };
  66326. /**
  66327. * Load a scene into an asset container
  66328. * @param rootUrl a string that defines the root url for scene and resources
  66329. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66330. * @param scene is the instance of BABYLON.Scene to append to
  66331. * @param onProgress a callback with a progress event for each file being loaded
  66332. * @param pluginExtension the extension used to determine the plugin
  66333. * @returns The loaded asset container
  66334. */
  66335. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66336. if (onProgress === void 0) { onProgress = null; }
  66337. if (pluginExtension === void 0) { pluginExtension = null; }
  66338. return new Promise(function (resolve, reject) {
  66339. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66340. resolve(assetContainer);
  66341. }, onProgress, function (scene, message, exception) {
  66342. reject(exception || new Error(message));
  66343. }, pluginExtension);
  66344. });
  66345. };
  66346. // Flags
  66347. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66348. SceneLoader._ShowLoadingScreen = true;
  66349. SceneLoader._CleanBoneMatrixWeights = false;
  66350. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66351. // Members
  66352. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66353. SceneLoader._registeredPlugins = {};
  66354. return SceneLoader;
  66355. }());
  66356. BABYLON.SceneLoader = SceneLoader;
  66357. ;
  66358. })(BABYLON || (BABYLON = {}));
  66359. //# sourceMappingURL=babylon.sceneLoader.js.map
  66360. "use strict";
  66361. var BABYLON;
  66362. (function (BABYLON) {
  66363. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66364. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66365. var parsedMaterial = parsedData.materials[index];
  66366. if (parsedMaterial.id === id) {
  66367. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66368. }
  66369. }
  66370. return null;
  66371. };
  66372. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66373. for (var i in names) {
  66374. if (mesh.name === names[i]) {
  66375. hierarchyIds.push(mesh.id);
  66376. return true;
  66377. }
  66378. }
  66379. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66380. hierarchyIds.push(mesh.id);
  66381. return true;
  66382. }
  66383. return false;
  66384. };
  66385. var logOperation = function (operation, producer) {
  66386. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66387. };
  66388. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66389. if (addToScene === void 0) { addToScene = false; }
  66390. var container = new BABYLON.AssetContainer(scene);
  66391. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66392. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66393. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66394. // and avoid problems with multiple concurrent .babylon loads.
  66395. var log = "importScene has failed JSON parse";
  66396. try {
  66397. var parsedData = JSON.parse(data);
  66398. log = "";
  66399. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66400. var index;
  66401. var cache;
  66402. // Lights
  66403. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66404. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66405. var parsedLight = parsedData.lights[index];
  66406. var light = BABYLON.Light.Parse(parsedLight, scene);
  66407. if (light) {
  66408. container.lights.push(light);
  66409. log += (index === 0 ? "\n\tLights:" : "");
  66410. log += "\n\t\t" + light.toString(fullDetails);
  66411. }
  66412. }
  66413. }
  66414. // Animations
  66415. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66416. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66417. var parsedAnimation = parsedData.animations[index];
  66418. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66419. scene.animations.push(animation);
  66420. container.animations.push(animation);
  66421. log += (index === 0 ? "\n\tAnimations:" : "");
  66422. log += "\n\t\t" + animation.toString(fullDetails);
  66423. }
  66424. }
  66425. // Materials
  66426. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66427. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66428. var parsedMaterial = parsedData.materials[index];
  66429. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66430. container.materials.push(mat);
  66431. log += (index === 0 ? "\n\tMaterials:" : "");
  66432. log += "\n\t\t" + mat.toString(fullDetails);
  66433. }
  66434. }
  66435. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66436. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66437. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66438. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66439. container.multiMaterials.push(mmat);
  66440. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66441. log += "\n\t\t" + mmat.toString(fullDetails);
  66442. }
  66443. }
  66444. // Morph targets
  66445. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66446. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66447. var managerData = _a[_i];
  66448. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66449. }
  66450. }
  66451. // Skeletons
  66452. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66453. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66454. var parsedSkeleton = parsedData.skeletons[index];
  66455. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66456. container.skeletons.push(skeleton);
  66457. log += (index === 0 ? "\n\tSkeletons:" : "");
  66458. log += "\n\t\t" + skeleton.toString(fullDetails);
  66459. }
  66460. }
  66461. // Geometries
  66462. var geometries = parsedData.geometries;
  66463. if (geometries !== undefined && geometries !== null) {
  66464. var addedGeometry = new Array();
  66465. // Boxes
  66466. var boxes = geometries.boxes;
  66467. if (boxes !== undefined && boxes !== null) {
  66468. for (index = 0, cache = boxes.length; index < cache; index++) {
  66469. var parsedBox = boxes[index];
  66470. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66471. }
  66472. }
  66473. // Spheres
  66474. var spheres = geometries.spheres;
  66475. if (spheres !== undefined && spheres !== null) {
  66476. for (index = 0, cache = spheres.length; index < cache; index++) {
  66477. var parsedSphere = spheres[index];
  66478. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66479. }
  66480. }
  66481. // Cylinders
  66482. var cylinders = geometries.cylinders;
  66483. if (cylinders !== undefined && cylinders !== null) {
  66484. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66485. var parsedCylinder = cylinders[index];
  66486. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66487. }
  66488. }
  66489. // Toruses
  66490. var toruses = geometries.toruses;
  66491. if (toruses !== undefined && toruses !== null) {
  66492. for (index = 0, cache = toruses.length; index < cache; index++) {
  66493. var parsedTorus = toruses[index];
  66494. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66495. }
  66496. }
  66497. // Grounds
  66498. var grounds = geometries.grounds;
  66499. if (grounds !== undefined && grounds !== null) {
  66500. for (index = 0, cache = grounds.length; index < cache; index++) {
  66501. var parsedGround = grounds[index];
  66502. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66503. }
  66504. }
  66505. // Planes
  66506. var planes = geometries.planes;
  66507. if (planes !== undefined && planes !== null) {
  66508. for (index = 0, cache = planes.length; index < cache; index++) {
  66509. var parsedPlane = planes[index];
  66510. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66511. }
  66512. }
  66513. // TorusKnots
  66514. var torusKnots = geometries.torusKnots;
  66515. if (torusKnots !== undefined && torusKnots !== null) {
  66516. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66517. var parsedTorusKnot = torusKnots[index];
  66518. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66519. }
  66520. }
  66521. // VertexData
  66522. var vertexData = geometries.vertexData;
  66523. if (vertexData !== undefined && vertexData !== null) {
  66524. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66525. var parsedVertexData = vertexData[index];
  66526. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66527. }
  66528. }
  66529. addedGeometry.forEach(function (g) {
  66530. if (g) {
  66531. container.geometries.push(g);
  66532. }
  66533. });
  66534. }
  66535. // Transform nodes
  66536. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66537. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66538. var parsedTransformNode = parsedData.transformNodes[index];
  66539. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66540. container.transformNodes.push(node);
  66541. }
  66542. }
  66543. // Meshes
  66544. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66545. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66546. var parsedMesh = parsedData.meshes[index];
  66547. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66548. container.meshes.push(mesh);
  66549. log += (index === 0 ? "\n\tMeshes:" : "");
  66550. log += "\n\t\t" + mesh.toString(fullDetails);
  66551. }
  66552. }
  66553. // Cameras
  66554. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66555. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66556. var parsedCamera = parsedData.cameras[index];
  66557. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66558. container.cameras.push(camera);
  66559. log += (index === 0 ? "\n\tCameras:" : "");
  66560. log += "\n\t\t" + camera.toString(fullDetails);
  66561. }
  66562. }
  66563. // Browsing all the graph to connect the dots
  66564. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66565. var camera = scene.cameras[index];
  66566. if (camera._waitingParentId) {
  66567. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66568. camera._waitingParentId = null;
  66569. }
  66570. }
  66571. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66572. var light_1 = scene.lights[index];
  66573. if (light_1 && light_1._waitingParentId) {
  66574. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66575. light_1._waitingParentId = null;
  66576. }
  66577. }
  66578. // Sounds
  66579. // TODO: add sound
  66580. var loadedSounds = [];
  66581. var loadedSound;
  66582. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66583. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66584. var parsedSound = parsedData.sounds[index];
  66585. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66586. if (!parsedSound.url)
  66587. parsedSound.url = parsedSound.name;
  66588. if (!loadedSounds[parsedSound.url]) {
  66589. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66590. loadedSounds[parsedSound.url] = loadedSound;
  66591. container.sounds.push(loadedSound);
  66592. }
  66593. else {
  66594. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66595. }
  66596. }
  66597. else {
  66598. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66599. }
  66600. }
  66601. }
  66602. loadedSounds = [];
  66603. // Connect parents & children and parse actions
  66604. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66605. var transformNode = scene.transformNodes[index];
  66606. if (transformNode._waitingParentId) {
  66607. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  66608. transformNode._waitingParentId = null;
  66609. }
  66610. }
  66611. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66612. var mesh = scene.meshes[index];
  66613. if (mesh._waitingParentId) {
  66614. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  66615. mesh._waitingParentId = null;
  66616. }
  66617. if (mesh._waitingActions) {
  66618. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  66619. mesh._waitingActions = null;
  66620. }
  66621. }
  66622. // freeze world matrix application
  66623. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66624. var currentMesh = scene.meshes[index];
  66625. if (currentMesh._waitingFreezeWorldMatrix) {
  66626. currentMesh.freezeWorldMatrix();
  66627. currentMesh._waitingFreezeWorldMatrix = null;
  66628. }
  66629. else {
  66630. currentMesh.computeWorldMatrix(true);
  66631. }
  66632. }
  66633. // Particles Systems
  66634. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66635. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66636. var parsedParticleSystem = parsedData.particleSystems[index];
  66637. if (parsedParticleSystem.activeParticleCount) {
  66638. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66639. container.particleSystems.push(ps);
  66640. }
  66641. else {
  66642. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66643. container.particleSystems.push(ps);
  66644. }
  66645. }
  66646. }
  66647. // Lens flares
  66648. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  66649. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  66650. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  66651. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  66652. container.lensFlareSystems.push(lf);
  66653. }
  66654. }
  66655. // Shadows
  66656. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  66657. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  66658. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  66659. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  66660. container.shadowGenerators.push(sg);
  66661. }
  66662. }
  66663. // Lights exclusions / inclusions
  66664. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66665. var light_2 = scene.lights[index];
  66666. // Excluded check
  66667. if (light_2._excludedMeshesIds.length > 0) {
  66668. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  66669. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  66670. if (excludedMesh) {
  66671. light_2.excludedMeshes.push(excludedMesh);
  66672. }
  66673. }
  66674. light_2._excludedMeshesIds = [];
  66675. }
  66676. // Included check
  66677. if (light_2._includedOnlyMeshesIds.length > 0) {
  66678. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  66679. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  66680. if (includedOnlyMesh) {
  66681. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  66682. }
  66683. }
  66684. light_2._includedOnlyMeshesIds = [];
  66685. }
  66686. }
  66687. // Effect layers
  66688. if (parsedData.effectLayers) {
  66689. for (index = 0; index < parsedData.effectLayers.length; index++) {
  66690. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  66691. container.effectLayers.push(effectLayer);
  66692. }
  66693. }
  66694. // Actions (scene)
  66695. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  66696. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  66697. }
  66698. if (!addToScene) {
  66699. container.removeAllFromScene();
  66700. }
  66701. }
  66702. catch (err) {
  66703. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  66704. if (onError) {
  66705. onError(msg, err);
  66706. }
  66707. else {
  66708. BABYLON.Tools.Log(msg);
  66709. throw err;
  66710. }
  66711. }
  66712. finally {
  66713. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66714. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66715. }
  66716. }
  66717. return container;
  66718. };
  66719. BABYLON.SceneLoader.RegisterPlugin({
  66720. name: "babylon.js",
  66721. extensions: ".babylon",
  66722. canDirectLoad: function (data) {
  66723. if (data.indexOf("babylon") !== -1) {
  66724. return true;
  66725. }
  66726. return false;
  66727. },
  66728. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  66729. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66730. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66731. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66732. // and avoid problems with multiple concurrent .babylon loads.
  66733. var log = "importMesh has failed JSON parse";
  66734. try {
  66735. var parsedData = JSON.parse(data);
  66736. log = "";
  66737. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66738. if (!meshesNames) {
  66739. meshesNames = null;
  66740. }
  66741. else if (!Array.isArray(meshesNames)) {
  66742. meshesNames = [meshesNames];
  66743. }
  66744. var hierarchyIds = new Array();
  66745. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66746. var loadedSkeletonsIds = [];
  66747. var loadedMaterialsIds = [];
  66748. var index;
  66749. var cache;
  66750. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66751. var parsedMesh = parsedData.meshes[index];
  66752. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  66753. if (meshesNames !== null) {
  66754. // Remove found mesh name from list.
  66755. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  66756. }
  66757. //Geometry?
  66758. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  66759. //does the file contain geometries?
  66760. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  66761. //find the correct geometry and add it to the scene
  66762. var found = false;
  66763. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  66764. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  66765. return;
  66766. }
  66767. else {
  66768. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  66769. if (parsedGeometryData.id === parsedMesh.geometryId) {
  66770. switch (geometryType) {
  66771. case "boxes":
  66772. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  66773. break;
  66774. case "spheres":
  66775. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  66776. break;
  66777. case "cylinders":
  66778. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  66779. break;
  66780. case "toruses":
  66781. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  66782. break;
  66783. case "grounds":
  66784. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  66785. break;
  66786. case "planes":
  66787. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  66788. break;
  66789. case "torusKnots":
  66790. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  66791. break;
  66792. case "vertexData":
  66793. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  66794. break;
  66795. }
  66796. found = true;
  66797. }
  66798. });
  66799. }
  66800. });
  66801. if (found === false) {
  66802. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  66803. }
  66804. }
  66805. }
  66806. // Material ?
  66807. if (parsedMesh.materialId) {
  66808. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  66809. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66810. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  66811. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  66812. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  66813. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  66814. var subMatId = parsedMultiMaterial.materials[matIndex];
  66815. loadedMaterialsIds.push(subMatId);
  66816. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  66817. if (mat) {
  66818. log += "\n\tMaterial " + mat.toString(fullDetails);
  66819. }
  66820. }
  66821. loadedMaterialsIds.push(parsedMultiMaterial.id);
  66822. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66823. if (mmat) {
  66824. materialFound = true;
  66825. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  66826. }
  66827. break;
  66828. }
  66829. }
  66830. }
  66831. if (materialFound === false) {
  66832. loadedMaterialsIds.push(parsedMesh.materialId);
  66833. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  66834. if (!mat) {
  66835. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  66836. }
  66837. else {
  66838. log += "\n\tMaterial " + mat.toString(fullDetails);
  66839. }
  66840. }
  66841. }
  66842. // Skeleton ?
  66843. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66844. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  66845. if (skeletonAlreadyLoaded === false) {
  66846. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  66847. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  66848. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  66849. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66850. skeletons.push(skeleton);
  66851. loadedSkeletonsIds.push(parsedSkeleton.id);
  66852. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  66853. }
  66854. }
  66855. }
  66856. }
  66857. // Morph targets ?
  66858. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66859. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66860. var managerData = _a[_i];
  66861. BABYLON.MorphTargetManager.Parse(managerData, scene);
  66862. }
  66863. }
  66864. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66865. meshes.push(mesh);
  66866. log += "\n\tMesh " + mesh.toString(fullDetails);
  66867. }
  66868. }
  66869. // Connecting parents
  66870. var currentMesh;
  66871. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66872. currentMesh = scene.meshes[index];
  66873. if (currentMesh._waitingParentId) {
  66874. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  66875. currentMesh._waitingParentId = null;
  66876. }
  66877. }
  66878. // freeze and compute world matrix application
  66879. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66880. currentMesh = scene.meshes[index];
  66881. if (currentMesh._waitingFreezeWorldMatrix) {
  66882. currentMesh.freezeWorldMatrix();
  66883. currentMesh._waitingFreezeWorldMatrix = null;
  66884. }
  66885. else {
  66886. currentMesh.computeWorldMatrix(true);
  66887. }
  66888. }
  66889. }
  66890. // Particles
  66891. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66892. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66893. var parsedParticleSystem = parsedData.particleSystems[index];
  66894. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  66895. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  66896. }
  66897. }
  66898. }
  66899. return true;
  66900. }
  66901. catch (err) {
  66902. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  66903. if (onError) {
  66904. onError(msg, err);
  66905. }
  66906. else {
  66907. BABYLON.Tools.Log(msg);
  66908. throw err;
  66909. }
  66910. }
  66911. finally {
  66912. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66913. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66914. }
  66915. }
  66916. return false;
  66917. },
  66918. load: function (scene, data, rootUrl, onError) {
  66919. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66920. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66921. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66922. // and avoid problems with multiple concurrent .babylon loads.
  66923. var log = "importScene has failed JSON parse";
  66924. try {
  66925. var parsedData = JSON.parse(data);
  66926. log = "";
  66927. // Scene
  66928. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  66929. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  66930. }
  66931. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  66932. scene.autoClear = parsedData.autoClear;
  66933. }
  66934. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  66935. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  66936. }
  66937. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  66938. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  66939. }
  66940. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  66941. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  66942. }
  66943. // Fog
  66944. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  66945. scene.fogMode = parsedData.fogMode;
  66946. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  66947. scene.fogStart = parsedData.fogStart;
  66948. scene.fogEnd = parsedData.fogEnd;
  66949. scene.fogDensity = parsedData.fogDensity;
  66950. log += "\tFog mode for scene: ";
  66951. switch (scene.fogMode) {
  66952. // getters not compiling, so using hardcoded
  66953. case 1:
  66954. log += "exp\n";
  66955. break;
  66956. case 2:
  66957. log += "exp2\n";
  66958. break;
  66959. case 3:
  66960. log += "linear\n";
  66961. break;
  66962. }
  66963. }
  66964. //Physics
  66965. if (parsedData.physicsEnabled) {
  66966. var physicsPlugin;
  66967. if (parsedData.physicsEngine === "cannon") {
  66968. physicsPlugin = new BABYLON.CannonJSPlugin();
  66969. }
  66970. else if (parsedData.physicsEngine === "oimo") {
  66971. physicsPlugin = new BABYLON.OimoJSPlugin();
  66972. }
  66973. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  66974. //else - default engine, which is currently oimo
  66975. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  66976. scene.enablePhysics(physicsGravity, physicsPlugin);
  66977. }
  66978. // Metadata
  66979. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  66980. scene.metadata = parsedData.metadata;
  66981. }
  66982. //collisions, if defined. otherwise, default is true
  66983. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  66984. scene.collisionsEnabled = parsedData.collisionsEnabled;
  66985. }
  66986. scene.workerCollisions = !!parsedData.workerCollisions;
  66987. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  66988. if (!container) {
  66989. return false;
  66990. }
  66991. if (parsedData.autoAnimate) {
  66992. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  66993. }
  66994. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  66995. scene.setActiveCameraByID(parsedData.activeCameraID);
  66996. }
  66997. // Environment texture
  66998. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  66999. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67000. if (parsedData.createDefaultSkybox === true) {
  67001. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67002. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67003. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67004. }
  67005. }
  67006. // Finish
  67007. return true;
  67008. }
  67009. catch (err) {
  67010. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67011. if (onError) {
  67012. onError(msg, err);
  67013. }
  67014. else {
  67015. BABYLON.Tools.Log(msg);
  67016. throw err;
  67017. }
  67018. }
  67019. finally {
  67020. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67021. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67022. }
  67023. }
  67024. return false;
  67025. },
  67026. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67027. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67028. return container;
  67029. }
  67030. });
  67031. })(BABYLON || (BABYLON = {}));
  67032. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67033. "use strict";
  67034. var BABYLON;
  67035. (function (BABYLON) {
  67036. var FilesInput = /** @class */ (function () {
  67037. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67038. this.onProcessFileCallback = function () { return true; };
  67039. this._engine = engine;
  67040. this._currentScene = scene;
  67041. this._sceneLoadedCallback = sceneLoadedCallback;
  67042. this._progressCallback = progressCallback;
  67043. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67044. this._textureLoadingCallback = textureLoadingCallback;
  67045. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67046. this._onReloadCallback = onReloadCallback;
  67047. this._errorCallback = errorCallback;
  67048. }
  67049. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67050. var _this = this;
  67051. if (elementToMonitor) {
  67052. this._elementToMonitor = elementToMonitor;
  67053. this._dragEnterHandler = function (e) { _this.drag(e); };
  67054. this._dragOverHandler = function (e) { _this.drag(e); };
  67055. this._dropHandler = function (e) { _this.drop(e); };
  67056. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67057. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67058. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67059. }
  67060. };
  67061. FilesInput.prototype.dispose = function () {
  67062. if (!this._elementToMonitor) {
  67063. return;
  67064. }
  67065. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67066. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67067. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67068. };
  67069. FilesInput.prototype.renderFunction = function () {
  67070. if (this._additionalRenderLoopLogicCallback) {
  67071. this._additionalRenderLoopLogicCallback();
  67072. }
  67073. if (this._currentScene) {
  67074. if (this._textureLoadingCallback) {
  67075. var remaining = this._currentScene.getWaitingItemsCount();
  67076. if (remaining > 0) {
  67077. this._textureLoadingCallback(remaining);
  67078. }
  67079. }
  67080. this._currentScene.render();
  67081. }
  67082. };
  67083. FilesInput.prototype.drag = function (e) {
  67084. e.stopPropagation();
  67085. e.preventDefault();
  67086. };
  67087. FilesInput.prototype.drop = function (eventDrop) {
  67088. eventDrop.stopPropagation();
  67089. eventDrop.preventDefault();
  67090. this.loadFiles(eventDrop);
  67091. };
  67092. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67093. var _this = this;
  67094. var reader = folder.createReader();
  67095. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67096. reader.readEntries(function (entries) {
  67097. remaining.count += entries.length;
  67098. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67099. var entry = entries_1[_i];
  67100. if (entry.isFile) {
  67101. entry.file(function (file) {
  67102. file.correctName = relativePath + file.name;
  67103. files.push(file);
  67104. if (--remaining.count === 0) {
  67105. callback();
  67106. }
  67107. });
  67108. }
  67109. else if (entry.isDirectory) {
  67110. _this._traverseFolder(entry, files, remaining, callback);
  67111. }
  67112. }
  67113. if (--remaining.count) {
  67114. callback();
  67115. }
  67116. });
  67117. };
  67118. FilesInput.prototype._processFiles = function (files) {
  67119. for (var i = 0; i < files.length; i++) {
  67120. var name = files[i].correctName.toLowerCase();
  67121. var extension = name.split('.').pop();
  67122. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67123. continue;
  67124. }
  67125. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67126. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67127. this._sceneFileToLoad = files[i];
  67128. }
  67129. else {
  67130. FilesInput.FilesToLoad[name] = files[i];
  67131. }
  67132. }
  67133. };
  67134. FilesInput.prototype.loadFiles = function (event) {
  67135. var _this = this;
  67136. if (this._startingProcessingFilesCallback)
  67137. this._startingProcessingFilesCallback();
  67138. // Handling data transfer via drag'n'drop
  67139. if (event && event.dataTransfer && event.dataTransfer.files) {
  67140. this._filesToLoad = event.dataTransfer.files;
  67141. }
  67142. // Handling files from input files
  67143. if (event && event.target && event.target.files) {
  67144. this._filesToLoad = event.target.files;
  67145. }
  67146. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67147. var files_1 = new Array();
  67148. var folders = [];
  67149. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67150. for (var i = 0; i < this._filesToLoad.length; i++) {
  67151. var fileToLoad = this._filesToLoad[i];
  67152. var name_1 = fileToLoad.name.toLowerCase();
  67153. var entry = void 0;
  67154. fileToLoad.correctName = name_1;
  67155. if (items) {
  67156. var item = items[i];
  67157. if (item.getAsEntry) {
  67158. entry = item.getAsEntry();
  67159. }
  67160. else if (item.webkitGetAsEntry) {
  67161. entry = item.webkitGetAsEntry();
  67162. }
  67163. }
  67164. if (!entry) {
  67165. files_1.push(fileToLoad);
  67166. }
  67167. else {
  67168. if (entry.isDirectory) {
  67169. folders.push(entry);
  67170. }
  67171. else {
  67172. files_1.push(fileToLoad);
  67173. }
  67174. }
  67175. }
  67176. if (folders.length === 0) {
  67177. this._processFiles(files_1);
  67178. this._processReload();
  67179. }
  67180. else {
  67181. var remaining = { count: folders.length };
  67182. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67183. var folder = folders_1[_i];
  67184. this._traverseFolder(folder, files_1, remaining, function () {
  67185. _this._processFiles(files_1);
  67186. if (remaining.count === 0) {
  67187. _this._processReload();
  67188. }
  67189. });
  67190. }
  67191. }
  67192. }
  67193. };
  67194. FilesInput.prototype._processReload = function () {
  67195. if (this._onReloadCallback) {
  67196. this._onReloadCallback(this._sceneFileToLoad);
  67197. }
  67198. else {
  67199. this.reload();
  67200. }
  67201. };
  67202. FilesInput.prototype.reload = function () {
  67203. var _this = this;
  67204. // If a scene file has been provided
  67205. if (this._sceneFileToLoad) {
  67206. if (this._currentScene) {
  67207. if (BABYLON.Tools.errorsCount > 0) {
  67208. BABYLON.Tools.ClearLogCache();
  67209. }
  67210. this._engine.stopRenderLoop();
  67211. this._currentScene.dispose();
  67212. }
  67213. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67214. if (_this._progressCallback) {
  67215. _this._progressCallback(progress);
  67216. }
  67217. }).then(function (scene) {
  67218. _this._currentScene = scene;
  67219. if (_this._sceneLoadedCallback) {
  67220. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67221. }
  67222. // Wait for textures and shaders to be ready
  67223. _this._currentScene.executeWhenReady(function () {
  67224. _this._engine.runRenderLoop(function () {
  67225. _this.renderFunction();
  67226. });
  67227. });
  67228. }).catch(function (error) {
  67229. if (_this._errorCallback) {
  67230. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67231. }
  67232. });
  67233. }
  67234. else {
  67235. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67236. }
  67237. };
  67238. FilesInput.FilesToLoad = {};
  67239. return FilesInput;
  67240. }());
  67241. BABYLON.FilesInput = FilesInput;
  67242. })(BABYLON || (BABYLON = {}));
  67243. //# sourceMappingURL=babylon.filesInput.js.map
  67244. "use strict";
  67245. var BABYLON;
  67246. (function (BABYLON) {
  67247. /**
  67248. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67249. * The underlying implementation relies on an associative array to ensure the best performances.
  67250. * The value can be anything including 'null' but except 'undefined'
  67251. */
  67252. var StringDictionary = /** @class */ (function () {
  67253. function StringDictionary() {
  67254. this._count = 0;
  67255. this._data = {};
  67256. }
  67257. /**
  67258. * This will clear this dictionary and copy the content from the 'source' one.
  67259. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67260. * @param source the dictionary to take the content from and copy to this dictionary
  67261. */
  67262. StringDictionary.prototype.copyFrom = function (source) {
  67263. var _this = this;
  67264. this.clear();
  67265. source.forEach(function (t, v) { return _this.add(t, v); });
  67266. };
  67267. /**
  67268. * Get a value based from its key
  67269. * @param key the given key to get the matching value from
  67270. * @return the value if found, otherwise undefined is returned
  67271. */
  67272. StringDictionary.prototype.get = function (key) {
  67273. var val = this._data[key];
  67274. if (val !== undefined) {
  67275. return val;
  67276. }
  67277. return undefined;
  67278. };
  67279. /**
  67280. * Get a value from its key or add it if it doesn't exist.
  67281. * This method will ensure you that a given key/data will be present in the dictionary.
  67282. * @param key the given key to get the matching value from
  67283. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67284. * The factory will only be invoked if there's no data for the given key.
  67285. * @return the value corresponding to the key.
  67286. */
  67287. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67288. var val = this.get(key);
  67289. if (val !== undefined) {
  67290. return val;
  67291. }
  67292. val = factory(key);
  67293. if (val) {
  67294. this.add(key, val);
  67295. }
  67296. return val;
  67297. };
  67298. /**
  67299. * Get a value from its key if present in the dictionary otherwise add it
  67300. * @param key the key to get the value from
  67301. * @param val if there's no such key/value pair in the dictionary add it with this value
  67302. * @return the value corresponding to the key
  67303. */
  67304. StringDictionary.prototype.getOrAdd = function (key, val) {
  67305. var curVal = this.get(key);
  67306. if (curVal !== undefined) {
  67307. return curVal;
  67308. }
  67309. this.add(key, val);
  67310. return val;
  67311. };
  67312. /**
  67313. * Check if there's a given key in the dictionary
  67314. * @param key the key to check for
  67315. * @return true if the key is present, false otherwise
  67316. */
  67317. StringDictionary.prototype.contains = function (key) {
  67318. return this._data[key] !== undefined;
  67319. };
  67320. /**
  67321. * Add a new key and its corresponding value
  67322. * @param key the key to add
  67323. * @param value the value corresponding to the key
  67324. * @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
  67325. */
  67326. StringDictionary.prototype.add = function (key, value) {
  67327. if (this._data[key] !== undefined) {
  67328. return false;
  67329. }
  67330. this._data[key] = value;
  67331. ++this._count;
  67332. return true;
  67333. };
  67334. StringDictionary.prototype.set = function (key, value) {
  67335. if (this._data[key] === undefined) {
  67336. return false;
  67337. }
  67338. this._data[key] = value;
  67339. return true;
  67340. };
  67341. /**
  67342. * Get the element of the given key and remove it from the dictionary
  67343. * @param key
  67344. */
  67345. StringDictionary.prototype.getAndRemove = function (key) {
  67346. var val = this.get(key);
  67347. if (val !== undefined) {
  67348. delete this._data[key];
  67349. --this._count;
  67350. return val;
  67351. }
  67352. return null;
  67353. };
  67354. /**
  67355. * Remove a key/value from the dictionary.
  67356. * @param key the key to remove
  67357. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67358. */
  67359. StringDictionary.prototype.remove = function (key) {
  67360. if (this.contains(key)) {
  67361. delete this._data[key];
  67362. --this._count;
  67363. return true;
  67364. }
  67365. return false;
  67366. };
  67367. /**
  67368. * Clear the whole content of the dictionary
  67369. */
  67370. StringDictionary.prototype.clear = function () {
  67371. this._data = {};
  67372. this._count = 0;
  67373. };
  67374. Object.defineProperty(StringDictionary.prototype, "count", {
  67375. get: function () {
  67376. return this._count;
  67377. },
  67378. enumerable: true,
  67379. configurable: true
  67380. });
  67381. /**
  67382. * Execute a callback on each key/val of the dictionary.
  67383. * Note that you can remove any element in this dictionary in the callback implementation
  67384. * @param callback the callback to execute on a given key/value pair
  67385. */
  67386. StringDictionary.prototype.forEach = function (callback) {
  67387. for (var cur in this._data) {
  67388. var val = this._data[cur];
  67389. callback(cur, val);
  67390. }
  67391. };
  67392. /**
  67393. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67394. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67395. * Note that you can remove any element in this dictionary in the callback implementation
  67396. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67397. */
  67398. StringDictionary.prototype.first = function (callback) {
  67399. for (var cur in this._data) {
  67400. var val = this._data[cur];
  67401. var res = callback(cur, val);
  67402. if (res) {
  67403. return res;
  67404. }
  67405. }
  67406. return null;
  67407. };
  67408. return StringDictionary;
  67409. }());
  67410. BABYLON.StringDictionary = StringDictionary;
  67411. })(BABYLON || (BABYLON = {}));
  67412. //# sourceMappingURL=babylon.stringDictionary.js.map
  67413. "use strict";
  67414. var BABYLON;
  67415. (function (BABYLON) {
  67416. var Tags = /** @class */ (function () {
  67417. function Tags() {
  67418. }
  67419. Tags.EnableFor = function (obj) {
  67420. obj._tags = obj._tags || {};
  67421. obj.hasTags = function () {
  67422. return Tags.HasTags(obj);
  67423. };
  67424. obj.addTags = function (tagsString) {
  67425. return Tags.AddTagsTo(obj, tagsString);
  67426. };
  67427. obj.removeTags = function (tagsString) {
  67428. return Tags.RemoveTagsFrom(obj, tagsString);
  67429. };
  67430. obj.matchesTagsQuery = function (tagsQuery) {
  67431. return Tags.MatchesQuery(obj, tagsQuery);
  67432. };
  67433. };
  67434. Tags.DisableFor = function (obj) {
  67435. delete obj._tags;
  67436. delete obj.hasTags;
  67437. delete obj.addTags;
  67438. delete obj.removeTags;
  67439. delete obj.matchesTagsQuery;
  67440. };
  67441. Tags.HasTags = function (obj) {
  67442. if (!obj._tags) {
  67443. return false;
  67444. }
  67445. return !BABYLON.Tools.IsEmpty(obj._tags);
  67446. };
  67447. Tags.GetTags = function (obj, asString) {
  67448. if (asString === void 0) { asString = true; }
  67449. if (!obj._tags) {
  67450. return null;
  67451. }
  67452. if (asString) {
  67453. var tagsArray = [];
  67454. for (var tag in obj._tags) {
  67455. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67456. tagsArray.push(tag);
  67457. }
  67458. }
  67459. return tagsArray.join(" ");
  67460. }
  67461. else {
  67462. return obj._tags;
  67463. }
  67464. };
  67465. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67466. // a tag cannot start with '||', '&&', and '!'
  67467. // it cannot contain whitespaces
  67468. Tags.AddTagsTo = function (obj, tagsString) {
  67469. if (!tagsString) {
  67470. return;
  67471. }
  67472. if (typeof tagsString !== "string") {
  67473. return;
  67474. }
  67475. var tags = tagsString.split(" ");
  67476. tags.forEach(function (tag, index, array) {
  67477. Tags._AddTagTo(obj, tag);
  67478. });
  67479. };
  67480. Tags._AddTagTo = function (obj, tag) {
  67481. tag = tag.trim();
  67482. if (tag === "" || tag === "true" || tag === "false") {
  67483. return;
  67484. }
  67485. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67486. return;
  67487. }
  67488. Tags.EnableFor(obj);
  67489. obj._tags[tag] = true;
  67490. };
  67491. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67492. if (!Tags.HasTags(obj)) {
  67493. return;
  67494. }
  67495. var tags = tagsString.split(" ");
  67496. for (var t in tags) {
  67497. Tags._RemoveTagFrom(obj, tags[t]);
  67498. }
  67499. };
  67500. Tags._RemoveTagFrom = function (obj, tag) {
  67501. delete obj._tags[tag];
  67502. };
  67503. Tags.MatchesQuery = function (obj, tagsQuery) {
  67504. if (tagsQuery === undefined) {
  67505. return true;
  67506. }
  67507. if (tagsQuery === "") {
  67508. return Tags.HasTags(obj);
  67509. }
  67510. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67511. };
  67512. return Tags;
  67513. }());
  67514. BABYLON.Tags = Tags;
  67515. })(BABYLON || (BABYLON = {}));
  67516. //# sourceMappingURL=babylon.tags.js.map
  67517. "use strict";
  67518. var BABYLON;
  67519. (function (BABYLON) {
  67520. var AndOrNotEvaluator = /** @class */ (function () {
  67521. function AndOrNotEvaluator() {
  67522. }
  67523. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67524. if (!query.match(/\([^\(\)]*\)/g)) {
  67525. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67526. }
  67527. else {
  67528. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67529. // remove parenthesis
  67530. r = r.slice(1, r.length - 1);
  67531. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67532. });
  67533. }
  67534. if (query === "true") {
  67535. return true;
  67536. }
  67537. if (query === "false") {
  67538. return false;
  67539. }
  67540. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67541. };
  67542. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67543. evaluateCallback = evaluateCallback || (function (r) {
  67544. return r === "true" ? true : false;
  67545. });
  67546. var result;
  67547. var or = parenthesisContent.split("||");
  67548. for (var i in or) {
  67549. if (or.hasOwnProperty(i)) {
  67550. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67551. var and = ori.split("&&");
  67552. if (and.length > 1) {
  67553. for (var j = 0; j < and.length; ++j) {
  67554. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67555. if (andj !== "true" && andj !== "false") {
  67556. if (andj[0] === "!") {
  67557. result = !evaluateCallback(andj.substring(1));
  67558. }
  67559. else {
  67560. result = evaluateCallback(andj);
  67561. }
  67562. }
  67563. else {
  67564. result = andj === "true" ? true : false;
  67565. }
  67566. if (!result) {
  67567. ori = "false";
  67568. break;
  67569. }
  67570. }
  67571. }
  67572. if (result || ori === "true") {
  67573. result = true;
  67574. break;
  67575. }
  67576. // result equals false (or undefined)
  67577. if (ori !== "true" && ori !== "false") {
  67578. if (ori[0] === "!") {
  67579. result = !evaluateCallback(ori.substring(1));
  67580. }
  67581. else {
  67582. result = evaluateCallback(ori);
  67583. }
  67584. }
  67585. else {
  67586. result = ori === "true" ? true : false;
  67587. }
  67588. }
  67589. }
  67590. // the whole parenthesis scope is replaced by 'true' or 'false'
  67591. return result ? "true" : "false";
  67592. };
  67593. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67594. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67595. // remove whitespaces
  67596. r = r.replace(/[\s]/g, function () { return ""; });
  67597. return r.length % 2 ? "!" : "";
  67598. });
  67599. booleanString = booleanString.trim();
  67600. if (booleanString === "!true") {
  67601. booleanString = "false";
  67602. }
  67603. else if (booleanString === "!false") {
  67604. booleanString = "true";
  67605. }
  67606. return booleanString;
  67607. };
  67608. return AndOrNotEvaluator;
  67609. }());
  67610. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  67611. })(BABYLON || (BABYLON = {}));
  67612. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  67613. "use strict";
  67614. var BABYLON;
  67615. (function (BABYLON) {
  67616. var Database = /** @class */ (function () {
  67617. function Database(urlToScene, callbackManifestChecked) {
  67618. // Handling various flavors of prefixed version of IndexedDB
  67619. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  67620. this.callbackManifestChecked = callbackManifestChecked;
  67621. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  67622. this.db = null;
  67623. this._enableSceneOffline = false;
  67624. this._enableTexturesOffline = false;
  67625. this.manifestVersionFound = 0;
  67626. this.mustUpdateRessources = false;
  67627. this.hasReachedQuota = false;
  67628. if (!Database.IDBStorageEnabled) {
  67629. this.callbackManifestChecked(true);
  67630. }
  67631. else {
  67632. this.checkManifestFile();
  67633. }
  67634. }
  67635. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  67636. get: function () {
  67637. return this._enableSceneOffline;
  67638. },
  67639. enumerable: true,
  67640. configurable: true
  67641. });
  67642. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  67643. get: function () {
  67644. return this._enableTexturesOffline;
  67645. },
  67646. enumerable: true,
  67647. configurable: true
  67648. });
  67649. Database.prototype.checkManifestFile = function () {
  67650. var _this = this;
  67651. var noManifestFile = function () {
  67652. _this._enableSceneOffline = false;
  67653. _this._enableTexturesOffline = false;
  67654. _this.callbackManifestChecked(false);
  67655. };
  67656. var timeStampUsed = false;
  67657. var manifestURL = this.currentSceneUrl + ".manifest";
  67658. var xhr = new XMLHttpRequest();
  67659. if (navigator.onLine) {
  67660. // Adding a timestamp to by-pass browsers' cache
  67661. timeStampUsed = true;
  67662. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  67663. }
  67664. xhr.open("GET", manifestURL, true);
  67665. xhr.addEventListener("load", function () {
  67666. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67667. try {
  67668. var manifestFile = JSON.parse(xhr.response);
  67669. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  67670. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  67671. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  67672. _this.manifestVersionFound = manifestFile.version;
  67673. }
  67674. if (_this.callbackManifestChecked) {
  67675. _this.callbackManifestChecked(true);
  67676. }
  67677. }
  67678. catch (ex) {
  67679. noManifestFile();
  67680. }
  67681. }
  67682. else {
  67683. noManifestFile();
  67684. }
  67685. }, false);
  67686. xhr.addEventListener("error", function (event) {
  67687. if (timeStampUsed) {
  67688. timeStampUsed = false;
  67689. // Let's retry without the timeStamp
  67690. // It could fail when coupled with HTML5 Offline API
  67691. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  67692. xhr.open("GET", retryManifestURL, true);
  67693. xhr.send();
  67694. }
  67695. else {
  67696. noManifestFile();
  67697. }
  67698. }, false);
  67699. try {
  67700. xhr.send();
  67701. }
  67702. catch (ex) {
  67703. BABYLON.Tools.Error("Error on XHR send request.");
  67704. this.callbackManifestChecked(false);
  67705. }
  67706. };
  67707. Database.prototype.openAsync = function (successCallback, errorCallback) {
  67708. var _this = this;
  67709. var handleError = function () {
  67710. _this.isSupported = false;
  67711. if (errorCallback)
  67712. errorCallback();
  67713. };
  67714. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  67715. // Your browser doesn't support IndexedDB
  67716. this.isSupported = false;
  67717. if (errorCallback)
  67718. errorCallback();
  67719. }
  67720. else {
  67721. // If the DB hasn't been opened or created yet
  67722. if (!this.db) {
  67723. this.hasReachedQuota = false;
  67724. this.isSupported = true;
  67725. var request = this.idbFactory.open("babylonjs", 1);
  67726. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  67727. request.onerror = function (event) {
  67728. handleError();
  67729. };
  67730. // executes when a version change transaction cannot complete due to other active transactions
  67731. request.onblocked = function (event) {
  67732. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  67733. handleError();
  67734. };
  67735. // DB has been opened successfully
  67736. request.onsuccess = function (event) {
  67737. _this.db = request.result;
  67738. successCallback();
  67739. };
  67740. // Initialization of the DB. Creating Scenes & Textures stores
  67741. request.onupgradeneeded = function (event) {
  67742. _this.db = (event.target).result;
  67743. if (_this.db) {
  67744. try {
  67745. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  67746. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  67747. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  67748. }
  67749. catch (ex) {
  67750. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  67751. handleError();
  67752. }
  67753. }
  67754. };
  67755. }
  67756. else {
  67757. if (successCallback)
  67758. successCallback();
  67759. }
  67760. }
  67761. };
  67762. Database.prototype.loadImageFromDB = function (url, image) {
  67763. var _this = this;
  67764. var completeURL = Database.ReturnFullUrlLocation(url);
  67765. var saveAndLoadImage = function () {
  67766. if (!_this.hasReachedQuota && _this.db !== null) {
  67767. // the texture is not yet in the DB, let's try to save it
  67768. _this._saveImageIntoDBAsync(completeURL, image);
  67769. }
  67770. else {
  67771. image.src = url;
  67772. }
  67773. };
  67774. if (!this.mustUpdateRessources) {
  67775. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  67776. }
  67777. else {
  67778. saveAndLoadImage();
  67779. }
  67780. };
  67781. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  67782. if (this.isSupported && this.db !== null) {
  67783. var texture;
  67784. var transaction = this.db.transaction(["textures"]);
  67785. transaction.onabort = function (event) {
  67786. image.src = url;
  67787. };
  67788. transaction.oncomplete = function (event) {
  67789. var blobTextureURL;
  67790. if (texture) {
  67791. var URL = window.URL || window.webkitURL;
  67792. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  67793. image.onerror = function () {
  67794. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  67795. image.src = url;
  67796. };
  67797. image.src = blobTextureURL;
  67798. }
  67799. else {
  67800. notInDBCallback();
  67801. }
  67802. };
  67803. var getRequest = transaction.objectStore("textures").get(url);
  67804. getRequest.onsuccess = function (event) {
  67805. texture = (event.target).result;
  67806. };
  67807. getRequest.onerror = function (event) {
  67808. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  67809. image.src = url;
  67810. };
  67811. }
  67812. else {
  67813. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67814. image.src = url;
  67815. }
  67816. };
  67817. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  67818. var _this = this;
  67819. if (this.isSupported) {
  67820. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  67821. var generateBlobUrl = function () {
  67822. var blobTextureURL;
  67823. if (blob) {
  67824. var URL = window.URL || window.webkitURL;
  67825. try {
  67826. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  67827. }
  67828. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  67829. catch (ex) {
  67830. blobTextureURL = URL.createObjectURL(blob);
  67831. }
  67832. }
  67833. if (blobTextureURL) {
  67834. image.src = blobTextureURL;
  67835. }
  67836. };
  67837. if (Database.IsUASupportingBlobStorage) {
  67838. var xhr = new XMLHttpRequest(), blob;
  67839. xhr.open("GET", url, true);
  67840. xhr.responseType = "blob";
  67841. xhr.addEventListener("load", function () {
  67842. if (xhr.status === 200 && _this.db) {
  67843. // Blob as response (XHR2)
  67844. blob = xhr.response;
  67845. var transaction = _this.db.transaction(["textures"], "readwrite");
  67846. // the transaction could abort because of a QuotaExceededError error
  67847. transaction.onabort = function (event) {
  67848. try {
  67849. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67850. var srcElement = (event.srcElement || event.target);
  67851. var error = srcElement.error;
  67852. if (error && error.name === "QuotaExceededError") {
  67853. _this.hasReachedQuota = true;
  67854. }
  67855. }
  67856. catch (ex) { }
  67857. generateBlobUrl();
  67858. };
  67859. transaction.oncomplete = function (event) {
  67860. generateBlobUrl();
  67861. };
  67862. var newTexture = { textureUrl: url, data: blob };
  67863. try {
  67864. // Put the blob into the dabase
  67865. var addRequest = transaction.objectStore("textures").put(newTexture);
  67866. addRequest.onsuccess = function (event) {
  67867. };
  67868. addRequest.onerror = function (event) {
  67869. generateBlobUrl();
  67870. };
  67871. }
  67872. catch (ex) {
  67873. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  67874. if (ex.code === 25) {
  67875. Database.IsUASupportingBlobStorage = false;
  67876. }
  67877. image.src = url;
  67878. }
  67879. }
  67880. else {
  67881. image.src = url;
  67882. }
  67883. }, false);
  67884. xhr.addEventListener("error", function (event) {
  67885. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  67886. image.src = url;
  67887. }, false);
  67888. xhr.send();
  67889. }
  67890. else {
  67891. image.src = url;
  67892. }
  67893. }
  67894. else {
  67895. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67896. image.src = url;
  67897. }
  67898. };
  67899. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  67900. var _this = this;
  67901. var updateVersion = function () {
  67902. // the version is not yet in the DB or we need to update it
  67903. _this._saveVersionIntoDBAsync(url, versionLoaded);
  67904. };
  67905. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  67906. };
  67907. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  67908. var _this = this;
  67909. if (this.isSupported && this.db) {
  67910. var version;
  67911. try {
  67912. var transaction = this.db.transaction(["versions"]);
  67913. transaction.oncomplete = function (event) {
  67914. if (version) {
  67915. // If the version in the JSON file is > than the version in DB
  67916. if (_this.manifestVersionFound > version.data) {
  67917. _this.mustUpdateRessources = true;
  67918. updateInDBCallback();
  67919. }
  67920. else {
  67921. callback(version.data);
  67922. }
  67923. }
  67924. else {
  67925. _this.mustUpdateRessources = true;
  67926. updateInDBCallback();
  67927. }
  67928. };
  67929. transaction.onabort = function (event) {
  67930. callback(-1);
  67931. };
  67932. var getRequest = transaction.objectStore("versions").get(url);
  67933. getRequest.onsuccess = function (event) {
  67934. version = (event.target).result;
  67935. };
  67936. getRequest.onerror = function (event) {
  67937. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  67938. callback(-1);
  67939. };
  67940. }
  67941. catch (ex) {
  67942. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  67943. callback(-1);
  67944. }
  67945. }
  67946. else {
  67947. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67948. callback(-1);
  67949. }
  67950. };
  67951. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  67952. var _this = this;
  67953. if (this.isSupported && !this.hasReachedQuota && this.db) {
  67954. try {
  67955. // Open a transaction to the database
  67956. var transaction = this.db.transaction(["versions"], "readwrite");
  67957. // the transaction could abort because of a QuotaExceededError error
  67958. transaction.onabort = function (event) {
  67959. try {
  67960. var error = event.srcElement['error'];
  67961. if (error && error.name === "QuotaExceededError") {
  67962. _this.hasReachedQuota = true;
  67963. }
  67964. }
  67965. catch (ex) { }
  67966. callback(-1);
  67967. };
  67968. transaction.oncomplete = function (event) {
  67969. callback(_this.manifestVersionFound);
  67970. };
  67971. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  67972. // Put the scene into the database
  67973. var addRequest = transaction.objectStore("versions").put(newVersion);
  67974. addRequest.onsuccess = function (event) {
  67975. };
  67976. addRequest.onerror = function (event) {
  67977. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  67978. };
  67979. }
  67980. catch (ex) {
  67981. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  67982. callback(-1);
  67983. }
  67984. }
  67985. else {
  67986. callback(-1);
  67987. }
  67988. };
  67989. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  67990. var _this = this;
  67991. var completeUrl = Database.ReturnFullUrlLocation(url);
  67992. var saveAndLoadFile = function () {
  67993. // the scene is not yet in the DB, let's try to save it
  67994. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  67995. };
  67996. this._checkVersionFromDB(completeUrl, function (version) {
  67997. if (version !== -1) {
  67998. if (!_this.mustUpdateRessources) {
  67999. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68000. }
  68001. else {
  68002. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68003. }
  68004. }
  68005. else {
  68006. if (errorCallback) {
  68007. errorCallback();
  68008. }
  68009. }
  68010. });
  68011. };
  68012. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68013. if (this.isSupported && this.db) {
  68014. var targetStore;
  68015. if (url.indexOf(".babylon") !== -1) {
  68016. targetStore = "scenes";
  68017. }
  68018. else {
  68019. targetStore = "textures";
  68020. }
  68021. var file;
  68022. var transaction = this.db.transaction([targetStore]);
  68023. transaction.oncomplete = function (event) {
  68024. if (file) {
  68025. callback(file.data);
  68026. }
  68027. else {
  68028. notInDBCallback();
  68029. }
  68030. };
  68031. transaction.onabort = function (event) {
  68032. notInDBCallback();
  68033. };
  68034. var getRequest = transaction.objectStore(targetStore).get(url);
  68035. getRequest.onsuccess = function (event) {
  68036. file = (event.target).result;
  68037. };
  68038. getRequest.onerror = function (event) {
  68039. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68040. notInDBCallback();
  68041. };
  68042. }
  68043. else {
  68044. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68045. callback();
  68046. }
  68047. };
  68048. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68049. var _this = this;
  68050. if (this.isSupported) {
  68051. var targetStore;
  68052. if (url.indexOf(".babylon") !== -1) {
  68053. targetStore = "scenes";
  68054. }
  68055. else {
  68056. targetStore = "textures";
  68057. }
  68058. // Create XHR
  68059. var xhr = new XMLHttpRequest();
  68060. var fileData;
  68061. xhr.open("GET", url, true);
  68062. if (useArrayBuffer) {
  68063. xhr.responseType = "arraybuffer";
  68064. }
  68065. if (progressCallback) {
  68066. xhr.onprogress = progressCallback;
  68067. }
  68068. xhr.addEventListener("load", function () {
  68069. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68070. // Blob as response (XHR2)
  68071. //fileData = xhr.responseText;
  68072. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68073. if (!_this.hasReachedQuota && _this.db) {
  68074. // Open a transaction to the database
  68075. var transaction = _this.db.transaction([targetStore], "readwrite");
  68076. // the transaction could abort because of a QuotaExceededError error
  68077. transaction.onabort = function (event) {
  68078. try {
  68079. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68080. var error = event.srcElement['error'];
  68081. if (error && error.name === "QuotaExceededError") {
  68082. _this.hasReachedQuota = true;
  68083. }
  68084. }
  68085. catch (ex) { }
  68086. callback(fileData);
  68087. };
  68088. transaction.oncomplete = function (event) {
  68089. callback(fileData);
  68090. };
  68091. var newFile;
  68092. if (targetStore === "scenes") {
  68093. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68094. }
  68095. else {
  68096. newFile = { textureUrl: url, data: fileData };
  68097. }
  68098. try {
  68099. // Put the scene into the database
  68100. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68101. addRequest.onsuccess = function (event) {
  68102. };
  68103. addRequest.onerror = function (event) {
  68104. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68105. };
  68106. }
  68107. catch (ex) {
  68108. callback(fileData);
  68109. }
  68110. }
  68111. else {
  68112. callback(fileData);
  68113. }
  68114. }
  68115. else {
  68116. callback();
  68117. }
  68118. }, false);
  68119. xhr.addEventListener("error", function (event) {
  68120. BABYLON.Tools.Error("error on XHR request.");
  68121. callback();
  68122. }, false);
  68123. xhr.send();
  68124. }
  68125. else {
  68126. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68127. callback();
  68128. }
  68129. };
  68130. Database.IsUASupportingBlobStorage = true;
  68131. Database.IDBStorageEnabled = true;
  68132. Database.parseURL = function (url) {
  68133. var a = document.createElement('a');
  68134. a.href = url;
  68135. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68136. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68137. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68138. return absLocation;
  68139. };
  68140. Database.ReturnFullUrlLocation = function (url) {
  68141. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68142. return (Database.parseURL(window.location.href) + url);
  68143. }
  68144. else {
  68145. return url;
  68146. }
  68147. };
  68148. return Database;
  68149. }());
  68150. BABYLON.Database = Database;
  68151. })(BABYLON || (BABYLON = {}));
  68152. //# sourceMappingURL=babylon.database.js.map
  68153. "use strict";
  68154. var BABYLON;
  68155. (function (BABYLON) {
  68156. var FresnelParameters = /** @class */ (function () {
  68157. function FresnelParameters() {
  68158. this._isEnabled = true;
  68159. this.leftColor = BABYLON.Color3.White();
  68160. this.rightColor = BABYLON.Color3.Black();
  68161. this.bias = 0;
  68162. this.power = 1;
  68163. }
  68164. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68165. get: function () {
  68166. return this._isEnabled;
  68167. },
  68168. set: function (value) {
  68169. if (this._isEnabled === value) {
  68170. return;
  68171. }
  68172. this._isEnabled = value;
  68173. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68174. },
  68175. enumerable: true,
  68176. configurable: true
  68177. });
  68178. FresnelParameters.prototype.clone = function () {
  68179. var newFresnelParameters = new FresnelParameters();
  68180. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68181. return newFresnelParameters;
  68182. };
  68183. FresnelParameters.prototype.serialize = function () {
  68184. var serializationObject = {};
  68185. serializationObject.isEnabled = this.isEnabled;
  68186. serializationObject.leftColor = this.leftColor.asArray();
  68187. serializationObject.rightColor = this.rightColor.asArray();
  68188. serializationObject.bias = this.bias;
  68189. serializationObject.power = this.power;
  68190. return serializationObject;
  68191. };
  68192. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68193. var fresnelParameters = new FresnelParameters();
  68194. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68195. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68196. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68197. fresnelParameters.bias = parsedFresnelParameters.bias;
  68198. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68199. return fresnelParameters;
  68200. };
  68201. return FresnelParameters;
  68202. }());
  68203. BABYLON.FresnelParameters = FresnelParameters;
  68204. })(BABYLON || (BABYLON = {}));
  68205. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68206. "use strict";
  68207. var BABYLON;
  68208. (function (BABYLON) {
  68209. var MultiMaterial = /** @class */ (function (_super) {
  68210. __extends(MultiMaterial, _super);
  68211. function MultiMaterial(name, scene) {
  68212. var _this = _super.call(this, name, scene, true) || this;
  68213. scene.multiMaterials.push(_this);
  68214. _this.subMaterials = new Array();
  68215. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68216. return _this;
  68217. }
  68218. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68219. get: function () {
  68220. return this._subMaterials;
  68221. },
  68222. set: function (value) {
  68223. this._subMaterials = value;
  68224. this._hookArray(value);
  68225. },
  68226. enumerable: true,
  68227. configurable: true
  68228. });
  68229. MultiMaterial.prototype._hookArray = function (array) {
  68230. var _this = this;
  68231. var oldPush = array.push;
  68232. array.push = function () {
  68233. var items = [];
  68234. for (var _i = 0; _i < arguments.length; _i++) {
  68235. items[_i] = arguments[_i];
  68236. }
  68237. var result = oldPush.apply(array, items);
  68238. _this._markAllSubMeshesAsTexturesDirty();
  68239. return result;
  68240. };
  68241. var oldSplice = array.splice;
  68242. array.splice = function (index, deleteCount) {
  68243. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68244. _this._markAllSubMeshesAsTexturesDirty();
  68245. return deleted;
  68246. };
  68247. };
  68248. // Properties
  68249. MultiMaterial.prototype.getSubMaterial = function (index) {
  68250. if (index < 0 || index >= this.subMaterials.length) {
  68251. return this.getScene().defaultMaterial;
  68252. }
  68253. return this.subMaterials[index];
  68254. };
  68255. MultiMaterial.prototype.getActiveTextures = function () {
  68256. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68257. if (subMaterial) {
  68258. return subMaterial.getActiveTextures();
  68259. }
  68260. else {
  68261. return [];
  68262. }
  68263. }));
  68264. var _a;
  68265. };
  68266. // Methods
  68267. MultiMaterial.prototype.getClassName = function () {
  68268. return "MultiMaterial";
  68269. };
  68270. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68271. for (var index = 0; index < this.subMaterials.length; index++) {
  68272. var subMaterial = this.subMaterials[index];
  68273. if (subMaterial) {
  68274. if (subMaterial.storeEffectOnSubMeshes) {
  68275. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68276. return false;
  68277. }
  68278. continue;
  68279. }
  68280. if (!subMaterial.isReady(mesh)) {
  68281. return false;
  68282. }
  68283. }
  68284. }
  68285. return true;
  68286. };
  68287. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68288. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68289. for (var index = 0; index < this.subMaterials.length; index++) {
  68290. var subMaterial = null;
  68291. var current = this.subMaterials[index];
  68292. if (cloneChildren && current) {
  68293. subMaterial = current.clone(name + "-" + current.name);
  68294. }
  68295. else {
  68296. subMaterial = this.subMaterials[index];
  68297. }
  68298. newMultiMaterial.subMaterials.push(subMaterial);
  68299. }
  68300. return newMultiMaterial;
  68301. };
  68302. MultiMaterial.prototype.serialize = function () {
  68303. var serializationObject = {};
  68304. serializationObject.name = this.name;
  68305. serializationObject.id = this.id;
  68306. if (BABYLON.Tags) {
  68307. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68308. }
  68309. serializationObject.materials = [];
  68310. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68311. var subMat = this.subMaterials[matIndex];
  68312. if (subMat) {
  68313. serializationObject.materials.push(subMat.id);
  68314. }
  68315. else {
  68316. serializationObject.materials.push(null);
  68317. }
  68318. }
  68319. return serializationObject;
  68320. };
  68321. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68322. var scene = this.getScene();
  68323. if (!scene) {
  68324. return;
  68325. }
  68326. var index = scene.multiMaterials.indexOf(this);
  68327. if (index >= 0) {
  68328. scene.multiMaterials.splice(index, 1);
  68329. }
  68330. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68331. };
  68332. return MultiMaterial;
  68333. }(BABYLON.Material));
  68334. BABYLON.MultiMaterial = MultiMaterial;
  68335. })(BABYLON || (BABYLON = {}));
  68336. //# sourceMappingURL=babylon.multiMaterial.js.map
  68337. "use strict";
  68338. var BABYLON;
  68339. (function (BABYLON) {
  68340. var FreeCameraTouchInput = /** @class */ (function () {
  68341. function FreeCameraTouchInput() {
  68342. this._offsetX = null;
  68343. this._offsetY = null;
  68344. this._pointerPressed = new Array();
  68345. this.touchAngularSensibility = 200000.0;
  68346. this.touchMoveSensibility = 250.0;
  68347. }
  68348. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68349. var _this = this;
  68350. var previousPosition = null;
  68351. if (this._pointerInput === undefined) {
  68352. this._onLostFocus = function (evt) {
  68353. _this._offsetX = null;
  68354. _this._offsetY = null;
  68355. };
  68356. this._pointerInput = function (p, s) {
  68357. var evt = p.event;
  68358. if (evt.pointerType === "mouse") {
  68359. return;
  68360. }
  68361. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68362. if (!noPreventDefault) {
  68363. evt.preventDefault();
  68364. }
  68365. _this._pointerPressed.push(evt.pointerId);
  68366. if (_this._pointerPressed.length !== 1) {
  68367. return;
  68368. }
  68369. previousPosition = {
  68370. x: evt.clientX,
  68371. y: evt.clientY
  68372. };
  68373. }
  68374. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68375. if (!noPreventDefault) {
  68376. evt.preventDefault();
  68377. }
  68378. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68379. if (index === -1) {
  68380. return;
  68381. }
  68382. _this._pointerPressed.splice(index, 1);
  68383. if (index != 0) {
  68384. return;
  68385. }
  68386. previousPosition = null;
  68387. _this._offsetX = null;
  68388. _this._offsetY = null;
  68389. }
  68390. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68391. if (!noPreventDefault) {
  68392. evt.preventDefault();
  68393. }
  68394. if (!previousPosition) {
  68395. return;
  68396. }
  68397. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68398. if (index != 0) {
  68399. return;
  68400. }
  68401. _this._offsetX = evt.clientX - previousPosition.x;
  68402. _this._offsetY = -(evt.clientY - previousPosition.y);
  68403. }
  68404. };
  68405. }
  68406. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68407. if (this._onLostFocus) {
  68408. element.addEventListener("blur", this._onLostFocus);
  68409. }
  68410. };
  68411. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68412. if (this._pointerInput && element) {
  68413. if (this._observer) {
  68414. this.camera.getScene().onPointerObservable.remove(this._observer);
  68415. this._observer = null;
  68416. }
  68417. if (this._onLostFocus) {
  68418. element.removeEventListener("blur", this._onLostFocus);
  68419. this._onLostFocus = null;
  68420. }
  68421. this._pointerPressed = [];
  68422. this._offsetX = null;
  68423. this._offsetY = null;
  68424. }
  68425. };
  68426. FreeCameraTouchInput.prototype.checkInputs = function () {
  68427. if (this._offsetX && this._offsetY) {
  68428. var camera = this.camera;
  68429. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68430. if (this._pointerPressed.length > 1) {
  68431. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68432. }
  68433. else {
  68434. var speed = camera._computeLocalCameraSpeed();
  68435. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68436. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68437. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68438. }
  68439. }
  68440. };
  68441. FreeCameraTouchInput.prototype.getClassName = function () {
  68442. return "FreeCameraTouchInput";
  68443. };
  68444. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68445. return "touch";
  68446. };
  68447. __decorate([
  68448. BABYLON.serialize()
  68449. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68450. __decorate([
  68451. BABYLON.serialize()
  68452. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68453. return FreeCameraTouchInput;
  68454. }());
  68455. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68456. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68457. })(BABYLON || (BABYLON = {}));
  68458. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68459. "use strict";
  68460. var BABYLON;
  68461. (function (BABYLON) {
  68462. // We're mainly based on the logic defined into the FreeCamera code
  68463. var TouchCamera = /** @class */ (function (_super) {
  68464. __extends(TouchCamera, _super);
  68465. //-- end properties for backward compatibility for inputs
  68466. function TouchCamera(name, position, scene) {
  68467. var _this = _super.call(this, name, position, scene) || this;
  68468. _this.inputs.addTouch();
  68469. _this._setupInputs();
  68470. return _this;
  68471. }
  68472. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68473. //-- Begin properties for backward compatibility for inputs
  68474. get: function () {
  68475. var touch = this.inputs.attached["touch"];
  68476. if (touch)
  68477. return touch.touchAngularSensibility;
  68478. return 0;
  68479. },
  68480. set: function (value) {
  68481. var touch = this.inputs.attached["touch"];
  68482. if (touch)
  68483. touch.touchAngularSensibility = value;
  68484. },
  68485. enumerable: true,
  68486. configurable: true
  68487. });
  68488. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68489. get: function () {
  68490. var touch = this.inputs.attached["touch"];
  68491. if (touch)
  68492. return touch.touchMoveSensibility;
  68493. return 0;
  68494. },
  68495. set: function (value) {
  68496. var touch = this.inputs.attached["touch"];
  68497. if (touch)
  68498. touch.touchMoveSensibility = value;
  68499. },
  68500. enumerable: true,
  68501. configurable: true
  68502. });
  68503. TouchCamera.prototype.getClassName = function () {
  68504. return "TouchCamera";
  68505. };
  68506. TouchCamera.prototype._setupInputs = function () {
  68507. var mouse = this.inputs.attached["mouse"];
  68508. if (mouse) {
  68509. mouse.touchEnabled = false;
  68510. }
  68511. };
  68512. return TouchCamera;
  68513. }(BABYLON.FreeCamera));
  68514. BABYLON.TouchCamera = TouchCamera;
  68515. })(BABYLON || (BABYLON = {}));
  68516. //# sourceMappingURL=babylon.touchCamera.js.map
  68517. "use strict";
  68518. var BABYLON;
  68519. (function (BABYLON) {
  68520. var ProceduralTexture = /** @class */ (function (_super) {
  68521. __extends(ProceduralTexture, _super);
  68522. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68523. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68524. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68525. if (isCube === void 0) { isCube = false; }
  68526. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68527. _this.isCube = isCube;
  68528. _this.isEnabled = true;
  68529. _this._currentRefreshId = -1;
  68530. _this._refreshRate = 1;
  68531. _this._vertexBuffers = {};
  68532. _this._uniforms = new Array();
  68533. _this._samplers = new Array();
  68534. _this._textures = {};
  68535. _this._floats = {};
  68536. _this._floatsArrays = {};
  68537. _this._colors3 = {};
  68538. _this._colors4 = {};
  68539. _this._vectors2 = {};
  68540. _this._vectors3 = {};
  68541. _this._matrices = {};
  68542. _this._fallbackTextureUsed = false;
  68543. scene.proceduralTextures.push(_this);
  68544. _this._engine = scene.getEngine();
  68545. _this.name = name;
  68546. _this.isRenderTarget = true;
  68547. _this._size = size;
  68548. _this._generateMipMaps = generateMipMaps;
  68549. _this.setFragment(fragment);
  68550. _this._fallbackTexture = fallbackTexture;
  68551. if (isCube) {
  68552. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68553. _this.setFloat("face", 0);
  68554. }
  68555. else {
  68556. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68557. }
  68558. // VBO
  68559. var vertices = [];
  68560. vertices.push(1, 1);
  68561. vertices.push(-1, 1);
  68562. vertices.push(-1, -1);
  68563. vertices.push(1, -1);
  68564. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68565. _this._createIndexBuffer();
  68566. return _this;
  68567. }
  68568. ProceduralTexture.prototype._createIndexBuffer = function () {
  68569. var engine = this._engine;
  68570. // Indices
  68571. var indices = [];
  68572. indices.push(0);
  68573. indices.push(1);
  68574. indices.push(2);
  68575. indices.push(0);
  68576. indices.push(2);
  68577. indices.push(3);
  68578. this._indexBuffer = engine.createIndexBuffer(indices);
  68579. };
  68580. ProceduralTexture.prototype._rebuild = function () {
  68581. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68582. if (vb) {
  68583. vb._rebuild();
  68584. }
  68585. this._createIndexBuffer();
  68586. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68587. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68588. }
  68589. };
  68590. ProceduralTexture.prototype.reset = function () {
  68591. if (this._effect === undefined) {
  68592. return;
  68593. }
  68594. var engine = this._engine;
  68595. engine._releaseEffect(this._effect);
  68596. };
  68597. ProceduralTexture.prototype.isReady = function () {
  68598. var _this = this;
  68599. var engine = this._engine;
  68600. var shaders;
  68601. if (!this._fragment) {
  68602. return false;
  68603. }
  68604. if (this._fallbackTextureUsed) {
  68605. return true;
  68606. }
  68607. if (this._fragment.fragmentElement !== undefined) {
  68608. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68609. }
  68610. else {
  68611. shaders = { vertex: "procedural", fragment: this._fragment };
  68612. }
  68613. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  68614. _this.releaseInternalTexture();
  68615. if (_this._fallbackTexture) {
  68616. _this._texture = _this._fallbackTexture._texture;
  68617. if (_this._texture) {
  68618. _this._texture.incrementReferences();
  68619. }
  68620. }
  68621. _this._fallbackTextureUsed = true;
  68622. });
  68623. return this._effect.isReady();
  68624. };
  68625. ProceduralTexture.prototype.resetRefreshCounter = function () {
  68626. this._currentRefreshId = -1;
  68627. };
  68628. ProceduralTexture.prototype.setFragment = function (fragment) {
  68629. this._fragment = fragment;
  68630. };
  68631. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  68632. get: function () {
  68633. return this._refreshRate;
  68634. },
  68635. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68636. set: function (value) {
  68637. this._refreshRate = value;
  68638. this.resetRefreshCounter();
  68639. },
  68640. enumerable: true,
  68641. configurable: true
  68642. });
  68643. ProceduralTexture.prototype._shouldRender = function () {
  68644. if (!this.isEnabled || !this.isReady() || !this._texture) {
  68645. return false;
  68646. }
  68647. if (this._fallbackTextureUsed) {
  68648. return false;
  68649. }
  68650. if (this._currentRefreshId === -1) {
  68651. this._currentRefreshId = 1;
  68652. return true;
  68653. }
  68654. if (this.refreshRate === this._currentRefreshId) {
  68655. this._currentRefreshId = 1;
  68656. return true;
  68657. }
  68658. this._currentRefreshId++;
  68659. return false;
  68660. };
  68661. ProceduralTexture.prototype.getRenderSize = function () {
  68662. return this._size;
  68663. };
  68664. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  68665. if (this._fallbackTextureUsed) {
  68666. return;
  68667. }
  68668. this.releaseInternalTexture();
  68669. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  68670. };
  68671. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  68672. if (this._uniforms.indexOf(uniformName) === -1) {
  68673. this._uniforms.push(uniformName);
  68674. }
  68675. };
  68676. ProceduralTexture.prototype.setTexture = function (name, texture) {
  68677. if (this._samplers.indexOf(name) === -1) {
  68678. this._samplers.push(name);
  68679. }
  68680. this._textures[name] = texture;
  68681. return this;
  68682. };
  68683. ProceduralTexture.prototype.setFloat = function (name, value) {
  68684. this._checkUniform(name);
  68685. this._floats[name] = value;
  68686. return this;
  68687. };
  68688. ProceduralTexture.prototype.setFloats = function (name, value) {
  68689. this._checkUniform(name);
  68690. this._floatsArrays[name] = value;
  68691. return this;
  68692. };
  68693. ProceduralTexture.prototype.setColor3 = function (name, value) {
  68694. this._checkUniform(name);
  68695. this._colors3[name] = value;
  68696. return this;
  68697. };
  68698. ProceduralTexture.prototype.setColor4 = function (name, value) {
  68699. this._checkUniform(name);
  68700. this._colors4[name] = value;
  68701. return this;
  68702. };
  68703. ProceduralTexture.prototype.setVector2 = function (name, value) {
  68704. this._checkUniform(name);
  68705. this._vectors2[name] = value;
  68706. return this;
  68707. };
  68708. ProceduralTexture.prototype.setVector3 = function (name, value) {
  68709. this._checkUniform(name);
  68710. this._vectors3[name] = value;
  68711. return this;
  68712. };
  68713. ProceduralTexture.prototype.setMatrix = function (name, value) {
  68714. this._checkUniform(name);
  68715. this._matrices[name] = value;
  68716. return this;
  68717. };
  68718. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68719. var scene = this.getScene();
  68720. if (!scene) {
  68721. return;
  68722. }
  68723. var engine = this._engine;
  68724. // Render
  68725. engine.enableEffect(this._effect);
  68726. engine.setState(false);
  68727. // Texture
  68728. for (var name in this._textures) {
  68729. this._effect.setTexture(name, this._textures[name]);
  68730. }
  68731. // Float
  68732. for (name in this._floats) {
  68733. this._effect.setFloat(name, this._floats[name]);
  68734. }
  68735. // Floats
  68736. for (name in this._floatsArrays) {
  68737. this._effect.setArray(name, this._floatsArrays[name]);
  68738. }
  68739. // Color3
  68740. for (name in this._colors3) {
  68741. this._effect.setColor3(name, this._colors3[name]);
  68742. }
  68743. // Color4
  68744. for (name in this._colors4) {
  68745. var color = this._colors4[name];
  68746. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  68747. }
  68748. // Vector2
  68749. for (name in this._vectors2) {
  68750. this._effect.setVector2(name, this._vectors2[name]);
  68751. }
  68752. // Vector3
  68753. for (name in this._vectors3) {
  68754. this._effect.setVector3(name, this._vectors3[name]);
  68755. }
  68756. // Matrix
  68757. for (name in this._matrices) {
  68758. this._effect.setMatrix(name, this._matrices[name]);
  68759. }
  68760. if (!this._texture) {
  68761. return;
  68762. }
  68763. if (this.isCube) {
  68764. for (var face = 0; face < 6; face++) {
  68765. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  68766. // VBOs
  68767. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68768. this._effect.setFloat("face", face);
  68769. // Clear
  68770. engine.clear(scene.clearColor, true, true, true);
  68771. // Draw order
  68772. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68773. // Mipmaps
  68774. if (face === 5) {
  68775. engine.generateMipMapsForCubemap(this._texture);
  68776. }
  68777. }
  68778. }
  68779. else {
  68780. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  68781. // VBOs
  68782. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68783. // Clear
  68784. engine.clear(scene.clearColor, true, true, true);
  68785. // Draw order
  68786. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68787. }
  68788. // Unbind
  68789. engine.unBindFramebuffer(this._texture, this.isCube);
  68790. if (this.onGenerated) {
  68791. this.onGenerated();
  68792. }
  68793. };
  68794. ProceduralTexture.prototype.clone = function () {
  68795. var textureSize = this.getSize();
  68796. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  68797. // Base texture
  68798. newTexture.hasAlpha = this.hasAlpha;
  68799. newTexture.level = this.level;
  68800. // RenderTarget Texture
  68801. newTexture.coordinatesMode = this.coordinatesMode;
  68802. return newTexture;
  68803. };
  68804. ProceduralTexture.prototype.dispose = function () {
  68805. var scene = this.getScene();
  68806. if (!scene) {
  68807. return;
  68808. }
  68809. var index = scene.proceduralTextures.indexOf(this);
  68810. if (index >= 0) {
  68811. scene.proceduralTextures.splice(index, 1);
  68812. }
  68813. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68814. if (vertexBuffer) {
  68815. vertexBuffer.dispose();
  68816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68817. }
  68818. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  68819. this._indexBuffer = null;
  68820. }
  68821. _super.prototype.dispose.call(this);
  68822. };
  68823. return ProceduralTexture;
  68824. }(BABYLON.Texture));
  68825. BABYLON.ProceduralTexture = ProceduralTexture;
  68826. })(BABYLON || (BABYLON = {}));
  68827. //# sourceMappingURL=babylon.proceduralTexture.js.map
  68828. "use strict";
  68829. var BABYLON;
  68830. (function (BABYLON) {
  68831. var CustomProceduralTexture = /** @class */ (function (_super) {
  68832. __extends(CustomProceduralTexture, _super);
  68833. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  68834. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  68835. _this._animate = true;
  68836. _this._time = 0;
  68837. _this._texturePath = texturePath;
  68838. //Try to load json
  68839. _this.loadJson(texturePath);
  68840. _this.refreshRate = 1;
  68841. return _this;
  68842. }
  68843. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  68844. var _this = this;
  68845. var noConfigFile = function () {
  68846. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  68847. try {
  68848. _this.setFragment(_this._texturePath);
  68849. }
  68850. catch (ex) {
  68851. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  68852. }
  68853. };
  68854. var configFileUrl = jsonUrl + "/config.json";
  68855. var xhr = new XMLHttpRequest();
  68856. xhr.open("GET", configFileUrl, true);
  68857. xhr.addEventListener("load", function () {
  68858. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68859. try {
  68860. _this._config = JSON.parse(xhr.response);
  68861. _this.updateShaderUniforms();
  68862. _this.updateTextures();
  68863. _this.setFragment(_this._texturePath + "/custom");
  68864. _this._animate = _this._config.animate;
  68865. _this.refreshRate = _this._config.refreshrate;
  68866. }
  68867. catch (ex) {
  68868. noConfigFile();
  68869. }
  68870. }
  68871. else {
  68872. noConfigFile();
  68873. }
  68874. }, false);
  68875. xhr.addEventListener("error", function () {
  68876. noConfigFile();
  68877. }, false);
  68878. try {
  68879. xhr.send();
  68880. }
  68881. catch (ex) {
  68882. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  68883. }
  68884. };
  68885. CustomProceduralTexture.prototype.isReady = function () {
  68886. if (!_super.prototype.isReady.call(this)) {
  68887. return false;
  68888. }
  68889. for (var name in this._textures) {
  68890. var texture = this._textures[name];
  68891. if (!texture.isReady()) {
  68892. return false;
  68893. }
  68894. }
  68895. return true;
  68896. };
  68897. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68898. var scene = this.getScene();
  68899. if (this._animate && scene) {
  68900. this._time += scene.getAnimationRatio() * 0.03;
  68901. this.updateShaderUniforms();
  68902. }
  68903. _super.prototype.render.call(this, useCameraPostProcess);
  68904. };
  68905. CustomProceduralTexture.prototype.updateTextures = function () {
  68906. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  68907. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  68908. }
  68909. };
  68910. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  68911. if (this._config) {
  68912. for (var j = 0; j < this._config.uniforms.length; j++) {
  68913. var uniform = this._config.uniforms[j];
  68914. switch (uniform.type) {
  68915. case "float":
  68916. this.setFloat(uniform.name, uniform.value);
  68917. break;
  68918. case "color3":
  68919. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  68920. break;
  68921. case "color4":
  68922. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  68923. break;
  68924. case "vector2":
  68925. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  68926. break;
  68927. case "vector3":
  68928. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  68929. break;
  68930. }
  68931. }
  68932. }
  68933. this.setFloat("time", this._time);
  68934. };
  68935. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  68936. get: function () {
  68937. return this._animate;
  68938. },
  68939. set: function (value) {
  68940. this._animate = value;
  68941. },
  68942. enumerable: true,
  68943. configurable: true
  68944. });
  68945. return CustomProceduralTexture;
  68946. }(BABYLON.ProceduralTexture));
  68947. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  68948. })(BABYLON || (BABYLON = {}));
  68949. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  68950. "use strict";
  68951. var BABYLON;
  68952. (function (BABYLON) {
  68953. var FreeCameraGamepadInput = /** @class */ (function () {
  68954. function FreeCameraGamepadInput() {
  68955. this.gamepadAngularSensibility = 200;
  68956. this.gamepadMoveSensibility = 40;
  68957. // private members
  68958. this._cameraTransform = BABYLON.Matrix.Identity();
  68959. this._deltaTransform = BABYLON.Vector3.Zero();
  68960. this._vector3 = BABYLON.Vector3.Zero();
  68961. this._vector2 = BABYLON.Vector2.Zero();
  68962. }
  68963. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68964. var _this = this;
  68965. var manager = this.camera.getScene().gamepadManager;
  68966. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68967. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68968. // prioritize XBOX gamepads.
  68969. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68970. _this.gamepad = gamepad;
  68971. }
  68972. }
  68973. });
  68974. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68975. if (_this.gamepad === gamepad) {
  68976. _this.gamepad = null;
  68977. }
  68978. });
  68979. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68980. };
  68981. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  68982. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68983. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68984. this.gamepad = null;
  68985. };
  68986. FreeCameraGamepadInput.prototype.checkInputs = function () {
  68987. if (this.gamepad && this.gamepad.leftStick) {
  68988. var camera = this.camera;
  68989. var LSValues = this.gamepad.leftStick;
  68990. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  68991. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68992. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  68993. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  68994. var RSValues = this.gamepad.rightStick;
  68995. if (RSValues) {
  68996. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  68997. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  68998. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  68999. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69000. }
  69001. else {
  69002. RSValues = { x: 0, y: 0 };
  69003. }
  69004. if (!camera.rotationQuaternion) {
  69005. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69006. }
  69007. else {
  69008. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69009. }
  69010. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69011. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69012. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69013. camera.cameraDirection.addInPlace(this._deltaTransform);
  69014. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69015. camera.cameraRotation.addInPlace(this._vector2);
  69016. }
  69017. };
  69018. FreeCameraGamepadInput.prototype.getClassName = function () {
  69019. return "FreeCameraGamepadInput";
  69020. };
  69021. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69022. return "gamepad";
  69023. };
  69024. __decorate([
  69025. BABYLON.serialize()
  69026. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69027. __decorate([
  69028. BABYLON.serialize()
  69029. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69030. return FreeCameraGamepadInput;
  69031. }());
  69032. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69033. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69034. })(BABYLON || (BABYLON = {}));
  69035. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69036. "use strict";
  69037. var BABYLON;
  69038. (function (BABYLON) {
  69039. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69040. function ArcRotateCameraGamepadInput() {
  69041. this.gamepadRotationSensibility = 80;
  69042. this.gamepadMoveSensibility = 40;
  69043. }
  69044. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69045. var _this = this;
  69046. var manager = this.camera.getScene().gamepadManager;
  69047. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69048. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69049. // prioritize XBOX gamepads.
  69050. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69051. _this.gamepad = gamepad;
  69052. }
  69053. }
  69054. });
  69055. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69056. if (_this.gamepad === gamepad) {
  69057. _this.gamepad = null;
  69058. }
  69059. });
  69060. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69061. };
  69062. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69063. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69064. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69065. this.gamepad = null;
  69066. };
  69067. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69068. if (this.gamepad) {
  69069. var camera = this.camera;
  69070. var RSValues = this.gamepad.rightStick;
  69071. if (RSValues) {
  69072. if (RSValues.x != 0) {
  69073. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69074. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69075. camera.inertialAlphaOffset += normalizedRX;
  69076. }
  69077. }
  69078. if (RSValues.y != 0) {
  69079. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69080. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69081. camera.inertialBetaOffset += normalizedRY;
  69082. }
  69083. }
  69084. }
  69085. var LSValues = this.gamepad.leftStick;
  69086. if (LSValues && LSValues.y != 0) {
  69087. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69088. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69089. this.camera.inertialRadiusOffset -= normalizedLY;
  69090. }
  69091. }
  69092. }
  69093. };
  69094. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69095. return "ArcRotateCameraGamepadInput";
  69096. };
  69097. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69098. return "gamepad";
  69099. };
  69100. __decorate([
  69101. BABYLON.serialize()
  69102. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69103. __decorate([
  69104. BABYLON.serialize()
  69105. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69106. return ArcRotateCameraGamepadInput;
  69107. }());
  69108. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69109. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69110. })(BABYLON || (BABYLON = {}));
  69111. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69112. "use strict";
  69113. var BABYLON;
  69114. (function (BABYLON) {
  69115. var GamepadManager = /** @class */ (function () {
  69116. function GamepadManager(_scene) {
  69117. var _this = this;
  69118. this._scene = _scene;
  69119. this._babylonGamepads = [];
  69120. this._oneGamepadConnected = false;
  69121. this._isMonitoring = false;
  69122. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69123. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69124. this._gamepadEventSupported = false;
  69125. }
  69126. else {
  69127. this._gamepadEventSupported = 'GamepadEvent' in window;
  69128. this._gamepadSupport = (navigator.getGamepads ||
  69129. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69130. }
  69131. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69132. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69133. for (var i in _this._babylonGamepads) {
  69134. var gamepad = _this._babylonGamepads[i];
  69135. if (gamepad && gamepad._isConnected) {
  69136. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69137. }
  69138. }
  69139. });
  69140. this._onGamepadConnectedEvent = function (evt) {
  69141. var gamepad = evt.gamepad;
  69142. if (gamepad.index in _this._babylonGamepads) {
  69143. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69144. return;
  69145. }
  69146. }
  69147. var newGamepad;
  69148. if (_this._babylonGamepads[gamepad.index]) {
  69149. newGamepad = _this._babylonGamepads[gamepad.index];
  69150. newGamepad.browserGamepad = gamepad;
  69151. newGamepad._isConnected = true;
  69152. }
  69153. else {
  69154. newGamepad = _this._addNewGamepad(gamepad);
  69155. }
  69156. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69157. _this._startMonitoringGamepads();
  69158. };
  69159. this._onGamepadDisconnectedEvent = function (evt) {
  69160. var gamepad = evt.gamepad;
  69161. // Remove the gamepad from the list of gamepads to monitor.
  69162. for (var i in _this._babylonGamepads) {
  69163. if (_this._babylonGamepads[i].index === gamepad.index) {
  69164. var disconnectedGamepad = _this._babylonGamepads[i];
  69165. disconnectedGamepad._isConnected = false;
  69166. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69167. break;
  69168. }
  69169. }
  69170. };
  69171. if (this._gamepadSupport) {
  69172. //first add already-connected gamepads
  69173. this._updateGamepadObjects();
  69174. if (this._babylonGamepads.length) {
  69175. this._startMonitoringGamepads();
  69176. }
  69177. // Checking if the gamepad connected event is supported (like in Firefox)
  69178. if (this._gamepadEventSupported) {
  69179. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69180. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69181. }
  69182. else {
  69183. this._startMonitoringGamepads();
  69184. }
  69185. }
  69186. }
  69187. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69188. get: function () {
  69189. return this._babylonGamepads;
  69190. },
  69191. enumerable: true,
  69192. configurable: true
  69193. });
  69194. GamepadManager.prototype.getGamepadByType = function (type) {
  69195. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69196. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69197. var gamepad = _a[_i];
  69198. if (gamepad && gamepad.type === type) {
  69199. return gamepad;
  69200. }
  69201. }
  69202. return null;
  69203. };
  69204. GamepadManager.prototype.dispose = function () {
  69205. if (this._gamepadEventSupported) {
  69206. if (this._onGamepadConnectedEvent) {
  69207. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69208. }
  69209. if (this._onGamepadDisconnectedEvent) {
  69210. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69211. }
  69212. this._onGamepadConnectedEvent = null;
  69213. this._onGamepadDisconnectedEvent = null;
  69214. }
  69215. this._babylonGamepads.forEach(function (gamepad) {
  69216. gamepad.dispose();
  69217. });
  69218. this.onGamepadConnectedObservable.clear();
  69219. this.onGamepadDisconnectedObservable.clear();
  69220. this._oneGamepadConnected = false;
  69221. this._stopMonitoringGamepads();
  69222. this._babylonGamepads = [];
  69223. };
  69224. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69225. if (!this._oneGamepadConnected) {
  69226. this._oneGamepadConnected = true;
  69227. }
  69228. var newGamepad;
  69229. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69230. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69231. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69232. }
  69233. else if (gamepad.pose) {
  69234. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69235. }
  69236. else {
  69237. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69238. }
  69239. this._babylonGamepads[newGamepad.index] = newGamepad;
  69240. return newGamepad;
  69241. };
  69242. GamepadManager.prototype._startMonitoringGamepads = function () {
  69243. if (!this._isMonitoring) {
  69244. this._isMonitoring = true;
  69245. //back-comp
  69246. if (!this._scene) {
  69247. this._checkGamepadsStatus();
  69248. }
  69249. }
  69250. };
  69251. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69252. this._isMonitoring = false;
  69253. };
  69254. GamepadManager.prototype._checkGamepadsStatus = function () {
  69255. var _this = this;
  69256. // Hack to be compatible Chrome
  69257. this._updateGamepadObjects();
  69258. for (var i in this._babylonGamepads) {
  69259. var gamepad = this._babylonGamepads[i];
  69260. if (!gamepad || !gamepad.isConnected) {
  69261. continue;
  69262. }
  69263. gamepad.update();
  69264. }
  69265. if (this._isMonitoring && !this._scene) {
  69266. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69267. }
  69268. };
  69269. // This function is called only on Chrome, which does not properly support
  69270. // connection/disconnection events and forces you to recopy again the gamepad object
  69271. GamepadManager.prototype._updateGamepadObjects = function () {
  69272. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69273. for (var i = 0; i < gamepads.length; i++) {
  69274. if (gamepads[i]) {
  69275. if (!this._babylonGamepads[gamepads[i].index]) {
  69276. var newGamepad = this._addNewGamepad(gamepads[i]);
  69277. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69278. }
  69279. else {
  69280. // Forced to copy again this object for Chrome for unknown reason
  69281. this._babylonGamepads[i].browserGamepad = gamepads[i];
  69282. if (!this._babylonGamepads[i].isConnected) {
  69283. this._babylonGamepads[i]._isConnected = true;
  69284. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69285. }
  69286. }
  69287. }
  69288. }
  69289. };
  69290. return GamepadManager;
  69291. }());
  69292. BABYLON.GamepadManager = GamepadManager;
  69293. })(BABYLON || (BABYLON = {}));
  69294. //# sourceMappingURL=babylon.gamepadManager.js.map
  69295. "use strict";
  69296. var BABYLON;
  69297. (function (BABYLON) {
  69298. var StickValues = /** @class */ (function () {
  69299. function StickValues(x, y) {
  69300. this.x = x;
  69301. this.y = y;
  69302. }
  69303. return StickValues;
  69304. }());
  69305. BABYLON.StickValues = StickValues;
  69306. var Gamepad = /** @class */ (function () {
  69307. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69308. if (leftStickX === void 0) { leftStickX = 0; }
  69309. if (leftStickY === void 0) { leftStickY = 1; }
  69310. if (rightStickX === void 0) { rightStickX = 2; }
  69311. if (rightStickY === void 0) { rightStickY = 3; }
  69312. this.id = id;
  69313. this.index = index;
  69314. this.browserGamepad = browserGamepad;
  69315. this._isConnected = true;
  69316. this._invertLeftStickY = false;
  69317. this.type = Gamepad.GAMEPAD;
  69318. this._leftStickAxisX = leftStickX;
  69319. this._leftStickAxisY = leftStickY;
  69320. this._rightStickAxisX = rightStickX;
  69321. this._rightStickAxisY = rightStickY;
  69322. if (this.browserGamepad.axes.length >= 2) {
  69323. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69324. }
  69325. if (this.browserGamepad.axes.length >= 4) {
  69326. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69327. }
  69328. }
  69329. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69330. get: function () {
  69331. return this._isConnected;
  69332. },
  69333. enumerable: true,
  69334. configurable: true
  69335. });
  69336. Gamepad.prototype.onleftstickchanged = function (callback) {
  69337. this._onleftstickchanged = callback;
  69338. };
  69339. Gamepad.prototype.onrightstickchanged = function (callback) {
  69340. this._onrightstickchanged = callback;
  69341. };
  69342. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69343. get: function () {
  69344. return this._leftStick;
  69345. },
  69346. set: function (newValues) {
  69347. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69348. this._onleftstickchanged(newValues);
  69349. }
  69350. this._leftStick = newValues;
  69351. },
  69352. enumerable: true,
  69353. configurable: true
  69354. });
  69355. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69356. get: function () {
  69357. return this._rightStick;
  69358. },
  69359. set: function (newValues) {
  69360. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69361. this._onrightstickchanged(newValues);
  69362. }
  69363. this._rightStick = newValues;
  69364. },
  69365. enumerable: true,
  69366. configurable: true
  69367. });
  69368. Gamepad.prototype.update = function () {
  69369. if (this._leftStick) {
  69370. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69371. if (this._invertLeftStickY) {
  69372. this.leftStick.y *= -1;
  69373. }
  69374. }
  69375. if (this._rightStick) {
  69376. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69377. }
  69378. };
  69379. Gamepad.prototype.dispose = function () {
  69380. };
  69381. Gamepad.GAMEPAD = 0;
  69382. Gamepad.GENERIC = 1;
  69383. Gamepad.XBOX = 2;
  69384. Gamepad.POSE_ENABLED = 3;
  69385. return Gamepad;
  69386. }());
  69387. BABYLON.Gamepad = Gamepad;
  69388. var GenericPad = /** @class */ (function (_super) {
  69389. __extends(GenericPad, _super);
  69390. function GenericPad(id, index, browserGamepad) {
  69391. var _this = _super.call(this, id, index, browserGamepad) || this;
  69392. _this.onButtonDownObservable = new BABYLON.Observable();
  69393. _this.onButtonUpObservable = new BABYLON.Observable();
  69394. _this.type = Gamepad.GENERIC;
  69395. _this._buttons = new Array(browserGamepad.buttons.length);
  69396. return _this;
  69397. }
  69398. GenericPad.prototype.onbuttondown = function (callback) {
  69399. this._onbuttondown = callback;
  69400. };
  69401. GenericPad.prototype.onbuttonup = function (callback) {
  69402. this._onbuttonup = callback;
  69403. };
  69404. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69405. if (newValue !== currentValue) {
  69406. if (newValue === 1) {
  69407. if (this._onbuttondown) {
  69408. this._onbuttondown(buttonIndex);
  69409. }
  69410. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69411. }
  69412. if (newValue === 0) {
  69413. if (this._onbuttonup) {
  69414. this._onbuttonup(buttonIndex);
  69415. }
  69416. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69417. }
  69418. }
  69419. return newValue;
  69420. };
  69421. GenericPad.prototype.update = function () {
  69422. _super.prototype.update.call(this);
  69423. for (var index = 0; index < this._buttons.length; index++) {
  69424. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69425. }
  69426. };
  69427. GenericPad.prototype.dispose = function () {
  69428. _super.prototype.dispose.call(this);
  69429. this.onButtonDownObservable.clear();
  69430. this.onButtonUpObservable.clear();
  69431. };
  69432. return GenericPad;
  69433. }(Gamepad));
  69434. BABYLON.GenericPad = GenericPad;
  69435. })(BABYLON || (BABYLON = {}));
  69436. //# sourceMappingURL=babylon.gamepad.js.map
  69437. "use strict";
  69438. var BABYLON;
  69439. (function (BABYLON) {
  69440. var Xbox360Button;
  69441. (function (Xbox360Button) {
  69442. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69443. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69444. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69445. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69446. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69447. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69448. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69449. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69450. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69451. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69452. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69453. var Xbox360Dpad;
  69454. (function (Xbox360Dpad) {
  69455. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69456. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69457. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69458. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69459. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69460. var Xbox360Pad = /** @class */ (function (_super) {
  69461. __extends(Xbox360Pad, _super);
  69462. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69463. if (xboxOne === void 0) { xboxOne = false; }
  69464. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69465. _this._leftTrigger = 0;
  69466. _this._rightTrigger = 0;
  69467. _this.onButtonDownObservable = new BABYLON.Observable();
  69468. _this.onButtonUpObservable = new BABYLON.Observable();
  69469. _this.onPadDownObservable = new BABYLON.Observable();
  69470. _this.onPadUpObservable = new BABYLON.Observable();
  69471. _this._buttonA = 0;
  69472. _this._buttonB = 0;
  69473. _this._buttonX = 0;
  69474. _this._buttonY = 0;
  69475. _this._buttonBack = 0;
  69476. _this._buttonStart = 0;
  69477. _this._buttonLB = 0;
  69478. _this._buttonRB = 0;
  69479. _this._buttonLeftStick = 0;
  69480. _this._buttonRightStick = 0;
  69481. _this._dPadUp = 0;
  69482. _this._dPadDown = 0;
  69483. _this._dPadLeft = 0;
  69484. _this._dPadRight = 0;
  69485. _this._isXboxOnePad = false;
  69486. _this.type = BABYLON.Gamepad.XBOX;
  69487. _this._isXboxOnePad = xboxOne;
  69488. return _this;
  69489. }
  69490. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69491. this._onlefttriggerchanged = callback;
  69492. };
  69493. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69494. this._onrighttriggerchanged = callback;
  69495. };
  69496. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69497. get: function () {
  69498. return this._leftTrigger;
  69499. },
  69500. set: function (newValue) {
  69501. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69502. this._onlefttriggerchanged(newValue);
  69503. }
  69504. this._leftTrigger = newValue;
  69505. },
  69506. enumerable: true,
  69507. configurable: true
  69508. });
  69509. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69510. get: function () {
  69511. return this._rightTrigger;
  69512. },
  69513. set: function (newValue) {
  69514. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  69515. this._onrighttriggerchanged(newValue);
  69516. }
  69517. this._rightTrigger = newValue;
  69518. },
  69519. enumerable: true,
  69520. configurable: true
  69521. });
  69522. Xbox360Pad.prototype.onbuttondown = function (callback) {
  69523. this._onbuttondown = callback;
  69524. };
  69525. Xbox360Pad.prototype.onbuttonup = function (callback) {
  69526. this._onbuttonup = callback;
  69527. };
  69528. Xbox360Pad.prototype.ondpaddown = function (callback) {
  69529. this._ondpaddown = callback;
  69530. };
  69531. Xbox360Pad.prototype.ondpadup = function (callback) {
  69532. this._ondpadup = callback;
  69533. };
  69534. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  69535. if (newValue !== currentValue) {
  69536. if (newValue === 1) {
  69537. if (this._onbuttondown) {
  69538. this._onbuttondown(buttonType);
  69539. }
  69540. this.onButtonDownObservable.notifyObservers(buttonType);
  69541. }
  69542. if (newValue === 0) {
  69543. if (this._onbuttonup) {
  69544. this._onbuttonup(buttonType);
  69545. }
  69546. this.onButtonUpObservable.notifyObservers(buttonType);
  69547. }
  69548. }
  69549. return newValue;
  69550. };
  69551. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  69552. if (newValue !== currentValue) {
  69553. if (newValue === 1) {
  69554. if (this._ondpaddown) {
  69555. this._ondpaddown(buttonType);
  69556. }
  69557. this.onPadDownObservable.notifyObservers(buttonType);
  69558. }
  69559. if (newValue === 0) {
  69560. if (this._ondpadup) {
  69561. this._ondpadup(buttonType);
  69562. }
  69563. this.onPadUpObservable.notifyObservers(buttonType);
  69564. }
  69565. }
  69566. return newValue;
  69567. };
  69568. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69569. get: function () {
  69570. return this._buttonA;
  69571. },
  69572. set: function (value) {
  69573. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69574. },
  69575. enumerable: true,
  69576. configurable: true
  69577. });
  69578. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69579. get: function () {
  69580. return this._buttonB;
  69581. },
  69582. set: function (value) {
  69583. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69584. },
  69585. enumerable: true,
  69586. configurable: true
  69587. });
  69588. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69589. get: function () {
  69590. return this._buttonX;
  69591. },
  69592. set: function (value) {
  69593. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69594. },
  69595. enumerable: true,
  69596. configurable: true
  69597. });
  69598. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69599. get: function () {
  69600. return this._buttonY;
  69601. },
  69602. set: function (value) {
  69603. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69604. },
  69605. enumerable: true,
  69606. configurable: true
  69607. });
  69608. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69609. get: function () {
  69610. return this._buttonStart;
  69611. },
  69612. set: function (value) {
  69613. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  69614. },
  69615. enumerable: true,
  69616. configurable: true
  69617. });
  69618. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  69619. get: function () {
  69620. return this._buttonBack;
  69621. },
  69622. set: function (value) {
  69623. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  69624. },
  69625. enumerable: true,
  69626. configurable: true
  69627. });
  69628. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  69629. get: function () {
  69630. return this._buttonLB;
  69631. },
  69632. set: function (value) {
  69633. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  69634. },
  69635. enumerable: true,
  69636. configurable: true
  69637. });
  69638. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  69639. get: function () {
  69640. return this._buttonRB;
  69641. },
  69642. set: function (value) {
  69643. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  69644. },
  69645. enumerable: true,
  69646. configurable: true
  69647. });
  69648. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  69649. get: function () {
  69650. return this._buttonLeftStick;
  69651. },
  69652. set: function (value) {
  69653. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  69654. },
  69655. enumerable: true,
  69656. configurable: true
  69657. });
  69658. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  69659. get: function () {
  69660. return this._buttonRightStick;
  69661. },
  69662. set: function (value) {
  69663. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  69664. },
  69665. enumerable: true,
  69666. configurable: true
  69667. });
  69668. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  69669. get: function () {
  69670. return this._dPadUp;
  69671. },
  69672. set: function (value) {
  69673. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  69674. },
  69675. enumerable: true,
  69676. configurable: true
  69677. });
  69678. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  69679. get: function () {
  69680. return this._dPadDown;
  69681. },
  69682. set: function (value) {
  69683. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  69684. },
  69685. enumerable: true,
  69686. configurable: true
  69687. });
  69688. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  69689. get: function () {
  69690. return this._dPadLeft;
  69691. },
  69692. set: function (value) {
  69693. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  69694. },
  69695. enumerable: true,
  69696. configurable: true
  69697. });
  69698. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  69699. get: function () {
  69700. return this._dPadRight;
  69701. },
  69702. set: function (value) {
  69703. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  69704. },
  69705. enumerable: true,
  69706. configurable: true
  69707. });
  69708. Xbox360Pad.prototype.update = function () {
  69709. _super.prototype.update.call(this);
  69710. if (this._isXboxOnePad) {
  69711. this.buttonA = this.browserGamepad.buttons[0].value;
  69712. this.buttonB = this.browserGamepad.buttons[1].value;
  69713. this.buttonX = this.browserGamepad.buttons[2].value;
  69714. this.buttonY = this.browserGamepad.buttons[3].value;
  69715. this.buttonLB = this.browserGamepad.buttons[4].value;
  69716. this.buttonRB = this.browserGamepad.buttons[5].value;
  69717. this.leftTrigger = this.browserGamepad.axes[2];
  69718. this.rightTrigger = this.browserGamepad.axes[5];
  69719. this.buttonBack = this.browserGamepad.buttons[9].value;
  69720. this.buttonStart = this.browserGamepad.buttons[8].value;
  69721. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  69722. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  69723. this.dPadUp = this.browserGamepad.buttons[11].value;
  69724. this.dPadDown = this.browserGamepad.buttons[12].value;
  69725. this.dPadLeft = this.browserGamepad.buttons[13].value;
  69726. this.dPadRight = this.browserGamepad.buttons[14].value;
  69727. }
  69728. else {
  69729. this.buttonA = this.browserGamepad.buttons[0].value;
  69730. this.buttonB = this.browserGamepad.buttons[1].value;
  69731. this.buttonX = this.browserGamepad.buttons[2].value;
  69732. this.buttonY = this.browserGamepad.buttons[3].value;
  69733. this.buttonLB = this.browserGamepad.buttons[4].value;
  69734. this.buttonRB = this.browserGamepad.buttons[5].value;
  69735. this.leftTrigger = this.browserGamepad.buttons[6].value;
  69736. this.rightTrigger = this.browserGamepad.buttons[7].value;
  69737. this.buttonBack = this.browserGamepad.buttons[8].value;
  69738. this.buttonStart = this.browserGamepad.buttons[9].value;
  69739. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  69740. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  69741. this.dPadUp = this.browserGamepad.buttons[12].value;
  69742. this.dPadDown = this.browserGamepad.buttons[13].value;
  69743. this.dPadLeft = this.browserGamepad.buttons[14].value;
  69744. this.dPadRight = this.browserGamepad.buttons[15].value;
  69745. }
  69746. };
  69747. Xbox360Pad.prototype.dispose = function () {
  69748. _super.prototype.dispose.call(this);
  69749. this.onButtonDownObservable.clear();
  69750. this.onButtonUpObservable.clear();
  69751. this.onPadDownObservable.clear();
  69752. this.onPadUpObservable.clear();
  69753. };
  69754. return Xbox360Pad;
  69755. }(BABYLON.Gamepad));
  69756. BABYLON.Xbox360Pad = Xbox360Pad;
  69757. })(BABYLON || (BABYLON = {}));
  69758. //# sourceMappingURL=babylon.xboxGamepad.js.map
  69759. "use strict";
  69760. var BABYLON;
  69761. (function (BABYLON) {
  69762. /**
  69763. * Defines the types of pose enabled controllers that are supported
  69764. */
  69765. var PoseEnabledControllerType;
  69766. (function (PoseEnabledControllerType) {
  69767. /**
  69768. * HTC Vive
  69769. */
  69770. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  69771. /**
  69772. * Oculus Rift
  69773. */
  69774. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  69775. /**
  69776. * Windows mixed reality
  69777. */
  69778. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  69779. /**
  69780. * Samsung gear VR
  69781. */
  69782. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  69783. /**
  69784. * Google Daydream
  69785. */
  69786. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  69787. /**
  69788. * Generic
  69789. */
  69790. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  69791. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  69792. /**
  69793. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69794. */
  69795. var PoseEnabledControllerHelper = /** @class */ (function () {
  69796. function PoseEnabledControllerHelper() {
  69797. }
  69798. /**
  69799. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69800. * @param vrGamepad the gamepad to initialized
  69801. * @returns a vr controller of the type the gamepad identified as
  69802. */
  69803. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  69804. // Oculus Touch
  69805. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  69806. return new BABYLON.OculusTouchController(vrGamepad);
  69807. }
  69808. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  69809. return new BABYLON.WindowsMotionController(vrGamepad);
  69810. }
  69811. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  69812. return new BABYLON.ViveController(vrGamepad);
  69813. }
  69814. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  69815. return new BABYLON.GearVRController(vrGamepad);
  69816. }
  69817. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  69818. return new BABYLON.DaydreamController(vrGamepad);
  69819. }
  69820. else {
  69821. return new BABYLON.GenericController(vrGamepad);
  69822. }
  69823. };
  69824. return PoseEnabledControllerHelper;
  69825. }());
  69826. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  69827. /**
  69828. * Defines the PoseEnabledController object that contains state of a vr capable controller
  69829. */
  69830. var PoseEnabledController = /** @class */ (function (_super) {
  69831. __extends(PoseEnabledController, _super);
  69832. /**
  69833. * Creates a new PoseEnabledController from a gamepad
  69834. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  69835. */
  69836. function PoseEnabledController(browserGamepad) {
  69837. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  69838. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  69839. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  69840. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  69841. /**
  69842. * The device position in babylon space
  69843. */
  69844. _this.devicePosition = BABYLON.Vector3.Zero();
  69845. /**
  69846. * The device rotation in babylon space
  69847. */
  69848. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69849. /**
  69850. * The scale factor of the device in babylon space
  69851. */
  69852. _this.deviceScaleFactor = 1;
  69853. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  69854. /**
  69855. * Internal, matrix used to convert room space to babylon space
  69856. */
  69857. _this._deviceToWorld = BABYLON.Matrix.Identity();
  69858. /**
  69859. * Node to be used when casting a ray from the controller
  69860. */
  69861. _this._pointingPoseNode = null;
  69862. _this._workingMatrix = BABYLON.Matrix.Identity();
  69863. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  69864. _this.controllerType = PoseEnabledControllerType.GENERIC;
  69865. _this.position = BABYLON.Vector3.Zero();
  69866. _this.rotationQuaternion = new BABYLON.Quaternion();
  69867. _this._calculatedPosition = BABYLON.Vector3.Zero();
  69868. _this._calculatedRotation = new BABYLON.Quaternion();
  69869. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  69870. return _this;
  69871. }
  69872. /**
  69873. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  69874. */
  69875. PoseEnabledController.prototype.update = function () {
  69876. _super.prototype.update.call(this);
  69877. var pose = this.browserGamepad.pose;
  69878. this.updateFromDevice(pose);
  69879. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  69880. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  69881. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  69882. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  69883. if (this._mesh) {
  69884. this._mesh.position.copyFrom(this.devicePosition);
  69885. if (this._mesh.rotationQuaternion) {
  69886. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69887. }
  69888. }
  69889. };
  69890. /**
  69891. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  69892. * @param poseData raw pose fromthe device
  69893. */
  69894. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  69895. if (poseData) {
  69896. this.rawPose = poseData;
  69897. if (poseData.position) {
  69898. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  69899. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  69900. this._deviceRoomPosition.z *= -1;
  69901. }
  69902. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  69903. this._calculatedPosition.addInPlace(this.position);
  69904. }
  69905. var pose = this.rawPose;
  69906. if (poseData.orientation && pose.orientation) {
  69907. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  69908. if (this._mesh) {
  69909. if (this._mesh.getScene().useRightHandedSystem) {
  69910. this._deviceRoomRotationQuaternion.z *= -1;
  69911. this._deviceRoomRotationQuaternion.w *= -1;
  69912. }
  69913. else {
  69914. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  69915. }
  69916. }
  69917. // if the camera is set, rotate to the camera's rotation
  69918. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  69919. }
  69920. }
  69921. };
  69922. /**
  69923. * Attaches a mesh to the controller
  69924. * @param mesh the mesh to be attached
  69925. */
  69926. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  69927. if (this._mesh) {
  69928. this._mesh.parent = null;
  69929. }
  69930. this._mesh = mesh;
  69931. if (this._poseControlledCamera) {
  69932. this._mesh.parent = this._poseControlledCamera;
  69933. }
  69934. if (!this._mesh.rotationQuaternion) {
  69935. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  69936. }
  69937. };
  69938. /**
  69939. * Attaches the controllers mesh to a camera
  69940. * @param camera the camera the mesh should be attached to
  69941. */
  69942. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  69943. this._poseControlledCamera = camera;
  69944. if (this._mesh) {
  69945. this._mesh.parent = this._poseControlledCamera;
  69946. }
  69947. };
  69948. /**
  69949. * Disposes of the controller
  69950. */
  69951. PoseEnabledController.prototype.dispose = function () {
  69952. if (this._mesh) {
  69953. this._mesh.dispose();
  69954. }
  69955. this._mesh = null;
  69956. _super.prototype.dispose.call(this);
  69957. };
  69958. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  69959. /**
  69960. * The mesh that is attached to the controller
  69961. */
  69962. get: function () {
  69963. return this._mesh;
  69964. },
  69965. enumerable: true,
  69966. configurable: true
  69967. });
  69968. /**
  69969. * Gets the ray of the controller in the direction the controller is pointing
  69970. * @param length the length the resulting ray should be
  69971. * @returns a ray in the direction the controller is pointing
  69972. */
  69973. PoseEnabledController.prototype.getForwardRay = function (length) {
  69974. if (length === void 0) { length = 100; }
  69975. if (!this.mesh) {
  69976. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  69977. }
  69978. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  69979. var origin = m.getTranslation();
  69980. var forward = new BABYLON.Vector3(0, 0, -1);
  69981. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69982. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69983. return new BABYLON.Ray(origin, direction, length);
  69984. };
  69985. /**
  69986. * Name of the child mesh that can be used to cast a ray from the controller
  69987. */
  69988. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  69989. return PoseEnabledController;
  69990. }(BABYLON.Gamepad));
  69991. BABYLON.PoseEnabledController = PoseEnabledController;
  69992. })(BABYLON || (BABYLON = {}));
  69993. //# sourceMappingURL=babylon.poseEnabledController.js.map
  69994. "use strict";
  69995. var BABYLON;
  69996. (function (BABYLON) {
  69997. /**
  69998. * Defines the WebVRController object that represents controllers tracked in 3D space
  69999. */
  70000. var WebVRController = /** @class */ (function (_super) {
  70001. __extends(WebVRController, _super);
  70002. /**
  70003. * Creates a new WebVRController from a gamepad
  70004. * @param vrGamepad the gamepad that the WebVRController should be created from
  70005. */
  70006. function WebVRController(vrGamepad) {
  70007. var _this = _super.call(this, vrGamepad) || this;
  70008. // Observables
  70009. /**
  70010. * Fired when the trigger state has changed
  70011. */
  70012. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70013. /**
  70014. * Fired when the main button state has changed
  70015. */
  70016. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70017. /**
  70018. * Fired when the secondary button state has changed
  70019. */
  70020. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70021. /**
  70022. * Fired when the pad state has changed
  70023. */
  70024. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70025. /**
  70026. * Fired when controllers stick values have changed
  70027. */
  70028. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70029. /**
  70030. * X and Y axis corrisponding to the controllers joystick
  70031. */
  70032. _this.pad = { x: 0, y: 0 };
  70033. // avoid GC, store state in a tmp object
  70034. _this._changes = {
  70035. pressChanged: false,
  70036. touchChanged: false,
  70037. valueChanged: false,
  70038. changed: false
  70039. };
  70040. _this._buttons = new Array(vrGamepad.buttons.length);
  70041. _this.hand = vrGamepad.hand;
  70042. return _this;
  70043. }
  70044. /**
  70045. * Fired when a controller button's state has changed
  70046. * @param callback the callback containing the button that was modified
  70047. */
  70048. WebVRController.prototype.onButtonStateChange = function (callback) {
  70049. this._onButtonStateChange = callback;
  70050. };
  70051. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70052. /**
  70053. * The default controller model for the controller
  70054. */
  70055. get: function () {
  70056. return this._defaultModel;
  70057. },
  70058. enumerable: true,
  70059. configurable: true
  70060. });
  70061. /**
  70062. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70063. */
  70064. WebVRController.prototype.update = function () {
  70065. _super.prototype.update.call(this);
  70066. for (var index = 0; index < this._buttons.length; index++) {
  70067. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70068. }
  70069. ;
  70070. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70071. this.pad.x = this.leftStick.x;
  70072. this.pad.y = this.leftStick.y;
  70073. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70074. }
  70075. };
  70076. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70077. if (!newState) {
  70078. newState = {
  70079. pressed: false,
  70080. touched: false,
  70081. value: 0
  70082. };
  70083. }
  70084. if (!currentState) {
  70085. this._buttons[buttonIndex] = {
  70086. pressed: newState.pressed,
  70087. touched: newState.touched,
  70088. value: newState.value
  70089. };
  70090. return;
  70091. }
  70092. this._checkChanges(newState, currentState);
  70093. if (this._changes.changed) {
  70094. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70095. this._handleButtonChange(buttonIndex, newState, this._changes);
  70096. }
  70097. this._buttons[buttonIndex].pressed = newState.pressed;
  70098. this._buttons[buttonIndex].touched = newState.touched;
  70099. // oculus triggers are never 0, thou not touched.
  70100. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70101. };
  70102. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70103. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70104. this._changes.touchChanged = newState.touched !== currentState.touched;
  70105. this._changes.valueChanged = newState.value !== currentState.value;
  70106. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70107. return this._changes;
  70108. };
  70109. /**
  70110. * Disposes of th webVRCOntroller
  70111. */
  70112. WebVRController.prototype.dispose = function () {
  70113. _super.prototype.dispose.call(this);
  70114. this.onTriggerStateChangedObservable.clear();
  70115. this.onMainButtonStateChangedObservable.clear();
  70116. this.onSecondaryButtonStateChangedObservable.clear();
  70117. this.onPadStateChangedObservable.clear();
  70118. this.onPadValuesChangedObservable.clear();
  70119. };
  70120. return WebVRController;
  70121. }(BABYLON.PoseEnabledController));
  70122. BABYLON.WebVRController = WebVRController;
  70123. })(BABYLON || (BABYLON = {}));
  70124. //# sourceMappingURL=babylon.webVRController.js.map
  70125. "use strict";
  70126. var BABYLON;
  70127. (function (BABYLON) {
  70128. /**
  70129. * Oculus Touch Controller
  70130. */
  70131. var OculusTouchController = /** @class */ (function (_super) {
  70132. __extends(OculusTouchController, _super);
  70133. /**
  70134. * Creates a new OculusTouchController from a gamepad
  70135. * @param vrGamepad the gamepad that the controller should be created from
  70136. */
  70137. function OculusTouchController(vrGamepad) {
  70138. var _this = _super.call(this, vrGamepad) || this;
  70139. /**
  70140. * Fired when the secondary trigger on this controller is modified
  70141. */
  70142. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70143. /**
  70144. * Fired when the thumb rest on this controller is modified
  70145. */
  70146. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70147. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70148. return _this;
  70149. }
  70150. /**
  70151. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70152. * @param scene scene in which to add meshes
  70153. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70154. */
  70155. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70156. var _this = this;
  70157. var meshName;
  70158. // Hand
  70159. if (this.hand === 'left') {
  70160. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70161. }
  70162. else {
  70163. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70164. }
  70165. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70166. /*
  70167. Parent Mesh name: oculus_touch_left
  70168. - body
  70169. - trigger
  70170. - thumbstick
  70171. - grip
  70172. - button_y
  70173. - button_x
  70174. - button_enter
  70175. */
  70176. _this._defaultModel = newMeshes[1];
  70177. _this.attachToMesh(_this._defaultModel);
  70178. if (meshLoaded) {
  70179. meshLoaded(_this._defaultModel);
  70180. }
  70181. });
  70182. };
  70183. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70184. /**
  70185. * Fired when the A button on this controller is modified
  70186. */
  70187. get: function () {
  70188. if (this.hand === 'right') {
  70189. return this.onMainButtonStateChangedObservable;
  70190. }
  70191. else {
  70192. throw new Error('No A button on left hand');
  70193. }
  70194. },
  70195. enumerable: true,
  70196. configurable: true
  70197. });
  70198. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70199. /**
  70200. * Fired when the B button on this controller is modified
  70201. */
  70202. get: function () {
  70203. if (this.hand === 'right') {
  70204. return this.onSecondaryButtonStateChangedObservable;
  70205. }
  70206. else {
  70207. throw new Error('No B button on left hand');
  70208. }
  70209. },
  70210. enumerable: true,
  70211. configurable: true
  70212. });
  70213. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70214. /**
  70215. * Fired when the X button on this controller is modified
  70216. */
  70217. get: function () {
  70218. if (this.hand === 'left') {
  70219. return this.onMainButtonStateChangedObservable;
  70220. }
  70221. else {
  70222. throw new Error('No X button on right hand');
  70223. }
  70224. },
  70225. enumerable: true,
  70226. configurable: true
  70227. });
  70228. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70229. /**
  70230. * Fired when the Y button on this controller is modified
  70231. */
  70232. get: function () {
  70233. if (this.hand === 'left') {
  70234. return this.onSecondaryButtonStateChangedObservable;
  70235. }
  70236. else {
  70237. throw new Error('No Y button on right hand');
  70238. }
  70239. },
  70240. enumerable: true,
  70241. configurable: true
  70242. });
  70243. /**
  70244. * Called once for each button that changed state since the last frame
  70245. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70246. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70247. * 2) secondary trigger (same)
  70248. * 3) A (right) X (left), touch, pressed = value
  70249. * 4) B / Y
  70250. * 5) thumb rest
  70251. * @param buttonIdx Which button index changed
  70252. * @param state New state of the button
  70253. * @param changes Which properties on the state changed since last frame
  70254. */
  70255. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70256. var notifyObject = state; //{ state: state, changes: changes };
  70257. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70258. switch (buttonIdx) {
  70259. case 0:
  70260. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70261. return;
  70262. case 1:// index trigger
  70263. if (this._defaultModel) {
  70264. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70265. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70266. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70267. }
  70268. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70269. return;
  70270. case 2:// secondary trigger
  70271. if (this._defaultModel) {
  70272. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70273. }
  70274. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70275. return;
  70276. case 3:
  70277. if (this._defaultModel) {
  70278. if (notifyObject.pressed) {
  70279. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70280. }
  70281. else {
  70282. (this._defaultModel.getChildren()[1]).position.y = 0;
  70283. }
  70284. }
  70285. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70286. return;
  70287. case 4:
  70288. if (this._defaultModel) {
  70289. if (notifyObject.pressed) {
  70290. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70291. }
  70292. else {
  70293. (this._defaultModel.getChildren()[2]).position.y = 0;
  70294. }
  70295. }
  70296. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70297. return;
  70298. case 5:
  70299. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70300. return;
  70301. }
  70302. };
  70303. /**
  70304. * Base Url for the controller model.
  70305. */
  70306. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70307. /**
  70308. * File name for the left controller model.
  70309. */
  70310. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70311. /**
  70312. * File name for the right controller model.
  70313. */
  70314. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70315. return OculusTouchController;
  70316. }(BABYLON.WebVRController));
  70317. BABYLON.OculusTouchController = OculusTouchController;
  70318. })(BABYLON || (BABYLON = {}));
  70319. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70320. "use strict";
  70321. var BABYLON;
  70322. (function (BABYLON) {
  70323. /**
  70324. * Vive Controller
  70325. */
  70326. var ViveController = /** @class */ (function (_super) {
  70327. __extends(ViveController, _super);
  70328. /**
  70329. * Creates a new ViveController from a gamepad
  70330. * @param vrGamepad the gamepad that the controller should be created from
  70331. */
  70332. function ViveController(vrGamepad) {
  70333. var _this = _super.call(this, vrGamepad) || this;
  70334. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70335. _this._invertLeftStickY = true;
  70336. return _this;
  70337. }
  70338. /**
  70339. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70340. * @param scene scene in which to add meshes
  70341. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70342. */
  70343. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70344. var _this = this;
  70345. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70346. /*
  70347. Parent Mesh name: ViveWand
  70348. - body
  70349. - r_gripper
  70350. - l_gripper
  70351. - menu_button
  70352. - system_button
  70353. - trackpad
  70354. - trigger
  70355. - LED
  70356. */
  70357. _this._defaultModel = newMeshes[1];
  70358. _this.attachToMesh(_this._defaultModel);
  70359. if (meshLoaded) {
  70360. meshLoaded(_this._defaultModel);
  70361. }
  70362. });
  70363. };
  70364. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70365. /**
  70366. * Fired when the left button on this controller is modified
  70367. */
  70368. get: function () {
  70369. return this.onMainButtonStateChangedObservable;
  70370. },
  70371. enumerable: true,
  70372. configurable: true
  70373. });
  70374. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70375. /**
  70376. * Fired when the right button on this controller is modified
  70377. */
  70378. get: function () {
  70379. return this.onMainButtonStateChangedObservable;
  70380. },
  70381. enumerable: true,
  70382. configurable: true
  70383. });
  70384. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70385. /**
  70386. * Fired when the menu button on this controller is modified
  70387. */
  70388. get: function () {
  70389. return this.onSecondaryButtonStateChangedObservable;
  70390. },
  70391. enumerable: true,
  70392. configurable: true
  70393. });
  70394. /**
  70395. * Called once for each button that changed state since the last frame
  70396. * Vive mapping:
  70397. * 0: touchpad
  70398. * 1: trigger
  70399. * 2: left AND right buttons
  70400. * 3: menu button
  70401. * @param buttonIdx Which button index changed
  70402. * @param state New state of the button
  70403. * @param changes Which properties on the state changed since last frame
  70404. */
  70405. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70406. var notifyObject = state; //{ state: state, changes: changes };
  70407. switch (buttonIdx) {
  70408. case 0:
  70409. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70410. return;
  70411. case 1:// index trigger
  70412. if (this._defaultModel) {
  70413. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70414. }
  70415. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70416. return;
  70417. case 2:// left AND right button
  70418. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70419. return;
  70420. case 3:
  70421. if (this._defaultModel) {
  70422. if (notifyObject.pressed) {
  70423. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70424. }
  70425. else {
  70426. (this._defaultModel.getChildren()[2]).position.y = 0;
  70427. }
  70428. }
  70429. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70430. return;
  70431. }
  70432. };
  70433. /**
  70434. * Base Url for the controller model.
  70435. */
  70436. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70437. /**
  70438. * File name for the controller model.
  70439. */
  70440. ViveController.MODEL_FILENAME = 'wand.babylon';
  70441. return ViveController;
  70442. }(BABYLON.WebVRController));
  70443. BABYLON.ViveController = ViveController;
  70444. })(BABYLON || (BABYLON = {}));
  70445. //# sourceMappingURL=babylon.viveController.js.map
  70446. "use strict";
  70447. var BABYLON;
  70448. (function (BABYLON) {
  70449. /**
  70450. * Generic Controller
  70451. */
  70452. var GenericController = /** @class */ (function (_super) {
  70453. __extends(GenericController, _super);
  70454. /**
  70455. * Creates a new GenericController from a gamepad
  70456. * @param vrGamepad the gamepad that the controller should be created from
  70457. */
  70458. function GenericController(vrGamepad) {
  70459. return _super.call(this, vrGamepad) || this;
  70460. }
  70461. /**
  70462. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70463. * @param scene scene in which to add meshes
  70464. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70465. */
  70466. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70467. var _this = this;
  70468. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70469. _this._defaultModel = newMeshes[1];
  70470. _this.attachToMesh(_this._defaultModel);
  70471. if (meshLoaded) {
  70472. meshLoaded(_this._defaultModel);
  70473. }
  70474. });
  70475. };
  70476. /**
  70477. * Called once for each button that changed state since the last frame
  70478. * @param buttonIdx Which button index changed
  70479. * @param state New state of the button
  70480. * @param changes Which properties on the state changed since last frame
  70481. */
  70482. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70483. console.log("Button id: " + buttonIdx + "state: ");
  70484. console.dir(state);
  70485. };
  70486. /**
  70487. * Base Url for the controller model.
  70488. */
  70489. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70490. /**
  70491. * File name for the controller model.
  70492. */
  70493. GenericController.MODEL_FILENAME = 'generic.babylon';
  70494. return GenericController;
  70495. }(BABYLON.WebVRController));
  70496. BABYLON.GenericController = GenericController;
  70497. })(BABYLON || (BABYLON = {}));
  70498. //# sourceMappingURL=babylon.genericController.js.map
  70499. "use strict";
  70500. var BABYLON;
  70501. (function (BABYLON) {
  70502. /**
  70503. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  70504. */
  70505. var LoadedMeshInfo = /** @class */ (function () {
  70506. function LoadedMeshInfo() {
  70507. /**
  70508. * Map of the button meshes contained in the controller
  70509. */
  70510. this.buttonMeshes = {};
  70511. /**
  70512. * Map of the axis meshes contained in the controller
  70513. */
  70514. this.axisMeshes = {};
  70515. }
  70516. return LoadedMeshInfo;
  70517. }());
  70518. /**
  70519. * Defines the WindowsMotionController object that the state of the windows motion controller
  70520. */
  70521. var WindowsMotionController = /** @class */ (function (_super) {
  70522. __extends(WindowsMotionController, _super);
  70523. /**
  70524. * Creates a new WindowsMotionController from a gamepad
  70525. * @param vrGamepad the gamepad that the controller should be created from
  70526. */
  70527. function WindowsMotionController(vrGamepad) {
  70528. var _this = _super.call(this, vrGamepad) || this;
  70529. _this._mapping = {
  70530. // Semantic button names
  70531. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  70532. // A mapping of the button name to glTF model node name
  70533. // that should be transformed by button value.
  70534. buttonMeshNames: {
  70535. 'trigger': 'SELECT',
  70536. 'menu': 'MENU',
  70537. 'grip': 'GRASP',
  70538. 'thumbstick': 'THUMBSTICK_PRESS',
  70539. 'trackpad': 'TOUCHPAD_PRESS'
  70540. },
  70541. // This mapping is used to translate from the Motion Controller to Babylon semantics
  70542. buttonObservableNames: {
  70543. 'trigger': 'onTriggerStateChangedObservable',
  70544. 'menu': 'onSecondaryButtonStateChangedObservable',
  70545. 'grip': 'onMainButtonStateChangedObservable',
  70546. 'thumbstick': 'onPadStateChangedObservable',
  70547. 'trackpad': 'onTrackpadChangedObservable'
  70548. },
  70549. // A mapping of the axis name to glTF model node name
  70550. // that should be transformed by axis value.
  70551. // This array mirrors the browserGamepad.axes array, such that
  70552. // the mesh corresponding to axis 0 is in this array index 0.
  70553. axisMeshNames: [
  70554. 'THUMBSTICK_X',
  70555. 'THUMBSTICK_Y',
  70556. 'TOUCHPAD_TOUCH_X',
  70557. 'TOUCHPAD_TOUCH_Y'
  70558. ],
  70559. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  70560. };
  70561. /**
  70562. * Fired when the trackpad on this controller is clicked
  70563. */
  70564. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70565. /**
  70566. * Fired when the trackpad on this controller is modified
  70567. */
  70568. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70569. /**
  70570. * The current x and y values of this controller's trackpad
  70571. */
  70572. _this.trackpad = { x: 0, y: 0 };
  70573. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70574. _this._loadedMeshInfo = null;
  70575. return _this;
  70576. }
  70577. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70578. /**
  70579. * Fired when the trigger on this controller is modified
  70580. */
  70581. get: function () {
  70582. return this.onTriggerStateChangedObservable;
  70583. },
  70584. enumerable: true,
  70585. configurable: true
  70586. });
  70587. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70588. /**
  70589. * Fired when the menu button on this controller is modified
  70590. */
  70591. get: function () {
  70592. return this.onSecondaryButtonStateChangedObservable;
  70593. },
  70594. enumerable: true,
  70595. configurable: true
  70596. });
  70597. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70598. /**
  70599. * Fired when the grip button on this controller is modified
  70600. */
  70601. get: function () {
  70602. return this.onMainButtonStateChangedObservable;
  70603. },
  70604. enumerable: true,
  70605. configurable: true
  70606. });
  70607. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70608. /**
  70609. * Fired when the thumbstick button on this controller is modified
  70610. */
  70611. get: function () {
  70612. return this.onPadStateChangedObservable;
  70613. },
  70614. enumerable: true,
  70615. configurable: true
  70616. });
  70617. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  70618. /**
  70619. * Fired when the touchpad button on this controller is modified
  70620. */
  70621. get: function () {
  70622. return this.onTrackpadChangedObservable;
  70623. },
  70624. enumerable: true,
  70625. configurable: true
  70626. });
  70627. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  70628. /**
  70629. * Fired when the touchpad values on this controller are modified
  70630. */
  70631. get: function () {
  70632. return this.onTrackpadValuesChangedObservable;
  70633. },
  70634. enumerable: true,
  70635. configurable: true
  70636. });
  70637. /**
  70638. * Called once per frame by the engine.
  70639. */
  70640. WindowsMotionController.prototype.update = function () {
  70641. _super.prototype.update.call(this);
  70642. if (this.browserGamepad.axes) {
  70643. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  70644. this.trackpad.x = this.browserGamepad["axes"][2];
  70645. this.trackpad.y = this.browserGamepad["axes"][3];
  70646. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  70647. }
  70648. // Only need to animate axes if there is a loaded mesh
  70649. if (this._loadedMeshInfo) {
  70650. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  70651. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  70652. }
  70653. }
  70654. }
  70655. };
  70656. /**
  70657. * Called once for each button that changed state since the last frame
  70658. * @param buttonIdx Which button index changed
  70659. * @param state New state of the button
  70660. * @param changes Which properties on the state changed since last frame
  70661. */
  70662. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70663. var buttonName = this._mapping.buttons[buttonIdx];
  70664. if (!buttonName) {
  70665. return;
  70666. }
  70667. // Only emit events for buttons that we know how to map from index to name
  70668. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  70669. if (observable) {
  70670. observable.notifyObservers(state);
  70671. }
  70672. this._lerpButtonTransform(buttonName, state.value);
  70673. };
  70674. /**
  70675. * Moves the buttons on the controller mesh based on their current state
  70676. * @param buttonName the name of the button to move
  70677. * @param buttonValue the value of the button which determines the buttons new position
  70678. */
  70679. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  70680. // If there is no loaded mesh, there is nothing to transform.
  70681. if (!this._loadedMeshInfo) {
  70682. return;
  70683. }
  70684. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  70685. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70686. return;
  70687. }
  70688. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  70689. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  70690. };
  70691. /**
  70692. * Moves the axis on the controller mesh based on its current state
  70693. * @param axis the index of the axis
  70694. * @param axisValue the value of the axis which determines the meshes new position
  70695. * @ignore
  70696. */
  70697. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  70698. if (!this._loadedMeshInfo) {
  70699. return;
  70700. }
  70701. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  70702. if (!meshInfo) {
  70703. return;
  70704. }
  70705. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70706. return;
  70707. }
  70708. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  70709. var lerpValue = axisValue * 0.5 + 0.5;
  70710. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  70711. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  70712. };
  70713. /**
  70714. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70715. * @param scene scene in which to add meshes
  70716. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70717. */
  70718. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  70719. var _this = this;
  70720. if (forceDefault === void 0) { forceDefault = false; }
  70721. var path;
  70722. var filename;
  70723. // Checking if GLB loader is present
  70724. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  70725. // Determine the device specific folder based on the ID suffix
  70726. var device = 'default';
  70727. if (this.id && !forceDefault) {
  70728. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  70729. device = ((match && match[0]) || device);
  70730. }
  70731. // Hand
  70732. if (this.hand === 'left') {
  70733. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  70734. }
  70735. else {
  70736. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  70737. }
  70738. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  70739. }
  70740. else {
  70741. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  70742. path = BABYLON.GenericController.MODEL_BASE_URL;
  70743. filename = BABYLON.GenericController.MODEL_FILENAME;
  70744. }
  70745. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  70746. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  70747. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  70748. if (!_this._loadedMeshInfo) {
  70749. return;
  70750. }
  70751. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  70752. _this.attachToMesh(_this._defaultModel);
  70753. if (meshLoaded) {
  70754. meshLoaded(_this._defaultModel);
  70755. }
  70756. }, null, function (scene, message) {
  70757. BABYLON.Tools.Log(message);
  70758. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  70759. if (!forceDefault) {
  70760. _this.initControllerMesh(scene, meshLoaded, true);
  70761. }
  70762. });
  70763. };
  70764. /**
  70765. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  70766. * can be transformed by button presses and axes values, based on this._mapping.
  70767. *
  70768. * @param scene scene in which the meshes exist
  70769. * @param meshes list of meshes that make up the controller model to process
  70770. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  70771. */
  70772. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  70773. var loadedMeshInfo = null;
  70774. // Create a new mesh to contain the glTF hierarchy
  70775. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  70776. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  70777. var childMesh = null;
  70778. for (var i = 0; i < meshes.length; i++) {
  70779. var mesh = meshes[i];
  70780. if (!mesh.parent) {
  70781. // Exclude controller meshes from picking results
  70782. mesh.isPickable = false;
  70783. // Handle root node, attach to the new parentMesh
  70784. childMesh = mesh;
  70785. break;
  70786. }
  70787. }
  70788. if (childMesh) {
  70789. childMesh.setParent(parentMesh);
  70790. // Create our mesh info. Note that this method will always return non-null.
  70791. loadedMeshInfo = this.createMeshInfo(parentMesh);
  70792. }
  70793. else {
  70794. BABYLON.Tools.Warn('Could not find root node in model file.');
  70795. }
  70796. return loadedMeshInfo;
  70797. };
  70798. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  70799. var loadedMeshInfo = new LoadedMeshInfo();
  70800. var i;
  70801. loadedMeshInfo.rootNode = rootNode;
  70802. // Reset the caches
  70803. loadedMeshInfo.buttonMeshes = {};
  70804. loadedMeshInfo.axisMeshes = {};
  70805. // Button Meshes
  70806. for (i = 0; i < this._mapping.buttons.length; i++) {
  70807. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  70808. if (!buttonMeshName) {
  70809. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  70810. continue;
  70811. }
  70812. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  70813. if (!buttonMesh) {
  70814. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  70815. continue;
  70816. }
  70817. var buttonMeshInfo = {
  70818. index: i,
  70819. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  70820. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  70821. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  70822. };
  70823. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  70824. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  70825. }
  70826. else {
  70827. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  70828. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  70829. '(VALUE: ' + !!buttonMeshInfo.value +
  70830. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  70831. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  70832. ')');
  70833. }
  70834. }
  70835. // Axis Meshes
  70836. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  70837. var axisMeshName = this._mapping.axisMeshNames[i];
  70838. if (!axisMeshName) {
  70839. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  70840. continue;
  70841. }
  70842. var axisMesh = getChildByName(rootNode, axisMeshName);
  70843. if (!axisMesh) {
  70844. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  70845. continue;
  70846. }
  70847. var axisMeshInfo = {
  70848. index: i,
  70849. value: getImmediateChildByName(axisMesh, 'VALUE'),
  70850. min: getImmediateChildByName(axisMesh, 'MIN'),
  70851. max: getImmediateChildByName(axisMesh, 'MAX')
  70852. };
  70853. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  70854. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  70855. }
  70856. else {
  70857. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  70858. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  70859. '(VALUE: ' + !!axisMeshInfo.value +
  70860. ', MIN: ' + !!axisMeshInfo.min +
  70861. ', MAX:' + !!axisMeshInfo.max +
  70862. ')');
  70863. }
  70864. }
  70865. // Pointing Ray
  70866. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  70867. if (!loadedMeshInfo.pointingPoseNode) {
  70868. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  70869. }
  70870. return loadedMeshInfo;
  70871. // Look through all children recursively. This will return null if no mesh exists with the given name.
  70872. function getChildByName(node, name) {
  70873. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  70874. }
  70875. // Look through only immediate children. This will return null if no mesh exists with the given name.
  70876. function getImmediateChildByName(node, name) {
  70877. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  70878. }
  70879. };
  70880. /**
  70881. * Gets the ray of the controller in the direction the controller is pointing
  70882. * @param length the length the resulting ray should be
  70883. * @returns a ray in the direction the controller is pointing
  70884. */
  70885. WindowsMotionController.prototype.getForwardRay = function (length) {
  70886. if (length === void 0) { length = 100; }
  70887. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  70888. return _super.prototype.getForwardRay.call(this, length);
  70889. }
  70890. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  70891. var origin = m.getTranslation();
  70892. var forward = new BABYLON.Vector3(0, 0, -1);
  70893. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70894. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70895. return new BABYLON.Ray(origin, direction, length);
  70896. };
  70897. /**
  70898. * Disposes of the controller
  70899. */
  70900. WindowsMotionController.prototype.dispose = function () {
  70901. _super.prototype.dispose.call(this);
  70902. this.onTrackpadChangedObservable.clear();
  70903. };
  70904. /**
  70905. * The base url used to load the left and right controller models
  70906. */
  70907. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  70908. /**
  70909. * The name of the left controller model file
  70910. */
  70911. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  70912. /**
  70913. * The name of the right controller model file
  70914. */
  70915. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  70916. /**
  70917. * The controller name prefix for this controller type
  70918. */
  70919. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  70920. /**
  70921. * The controller id pattern for this controller type
  70922. */
  70923. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  70924. return WindowsMotionController;
  70925. }(BABYLON.WebVRController));
  70926. BABYLON.WindowsMotionController = WindowsMotionController;
  70927. })(BABYLON || (BABYLON = {}));
  70928. //# sourceMappingURL=babylon.windowsMotionController.js.map
  70929. "use strict";
  70930. var BABYLON;
  70931. (function (BABYLON) {
  70932. /**
  70933. * Gear VR Controller
  70934. */
  70935. var GearVRController = /** @class */ (function (_super) {
  70936. __extends(GearVRController, _super);
  70937. /**
  70938. * Creates a new GearVRController from a gamepad
  70939. * @param vrGamepad the gamepad that the controller should be created from
  70940. */
  70941. function GearVRController(vrGamepad) {
  70942. var _this = _super.call(this, vrGamepad) || this;
  70943. _this._buttonIndexToObservableNameMap = [
  70944. 'onTrackpadChangedObservable',
  70945. 'onTriggerStateChangedObservable' // Trigger
  70946. ];
  70947. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  70948. return _this;
  70949. }
  70950. /**
  70951. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70952. * @param scene scene in which to add meshes
  70953. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70954. */
  70955. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70956. var _this = this;
  70957. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  70958. _this._defaultModel = newMeshes[1];
  70959. _this.attachToMesh(_this._defaultModel);
  70960. if (meshLoaded) {
  70961. meshLoaded(_this._defaultModel);
  70962. }
  70963. });
  70964. };
  70965. /**
  70966. * Called once for each button that changed state since the last frame
  70967. * @param buttonIdx Which button index changed
  70968. * @param state New state of the button
  70969. * @param changes Which properties on the state changed since last frame
  70970. */
  70971. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70972. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  70973. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  70974. // Only emit events for buttons that we know how to map from index to observable
  70975. var observable = this[observableName];
  70976. if (observable) {
  70977. observable.notifyObservers(state);
  70978. }
  70979. }
  70980. };
  70981. /**
  70982. * Base Url for the controller model.
  70983. */
  70984. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70985. /**
  70986. * File name for the controller model.
  70987. */
  70988. GearVRController.MODEL_FILENAME = 'generic.babylon';
  70989. /**
  70990. * Gamepad Id prefix used to identify this controller.
  70991. */
  70992. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  70993. return GearVRController;
  70994. }(BABYLON.WebVRController));
  70995. BABYLON.GearVRController = GearVRController;
  70996. })(BABYLON || (BABYLON = {}));
  70997. //# sourceMappingURL=babylon.gearVRController.js.map
  70998. "use strict";
  70999. var BABYLON;
  71000. (function (BABYLON) {
  71001. /**
  71002. * Google Daydream controller
  71003. */
  71004. var DaydreamController = /** @class */ (function (_super) {
  71005. __extends(DaydreamController, _super);
  71006. /**
  71007. * Creates a new DaydreamController from a gamepad
  71008. * @param vrGamepad the gamepad that the controller should be created from
  71009. */
  71010. function DaydreamController(vrGamepad) {
  71011. var _this = _super.call(this, vrGamepad) || this;
  71012. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71013. return _this;
  71014. }
  71015. /**
  71016. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71017. * @param scene scene in which to add meshes
  71018. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71019. */
  71020. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71021. var _this = this;
  71022. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71023. _this._defaultModel = newMeshes[1];
  71024. _this.attachToMesh(_this._defaultModel);
  71025. if (meshLoaded) {
  71026. meshLoaded(_this._defaultModel);
  71027. }
  71028. });
  71029. };
  71030. /**
  71031. * Called once for each button that changed state since the last frame
  71032. * @param buttonIdx Which button index changed
  71033. * @param state New state of the button
  71034. * @param changes Which properties on the state changed since last frame
  71035. */
  71036. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71037. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71038. if (buttonIdx === 0) {
  71039. var observable = this.onTriggerStateChangedObservable;
  71040. if (observable) {
  71041. observable.notifyObservers(state);
  71042. }
  71043. }
  71044. else {
  71045. // If the app or home buttons are ever made available
  71046. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71047. }
  71048. };
  71049. /**
  71050. * Base Url for the controller model.
  71051. */
  71052. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71053. /**
  71054. * File name for the controller model.
  71055. */
  71056. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71057. /**
  71058. * Gamepad Id prefix used to identify Daydream Controller.
  71059. */
  71060. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71061. return DaydreamController;
  71062. }(BABYLON.WebVRController));
  71063. BABYLON.DaydreamController = DaydreamController;
  71064. })(BABYLON || (BABYLON = {}));
  71065. //# sourceMappingURL=babylon.daydreamController.js.map
  71066. "use strict";
  71067. var BABYLON;
  71068. (function (BABYLON) {
  71069. var FollowCamera = /** @class */ (function (_super) {
  71070. __extends(FollowCamera, _super);
  71071. function FollowCamera(name, position, scene, lockedTarget) {
  71072. if (lockedTarget === void 0) { lockedTarget = null; }
  71073. var _this = _super.call(this, name, position, scene) || this;
  71074. _this.radius = 12;
  71075. _this.rotationOffset = 0;
  71076. _this.heightOffset = 4;
  71077. _this.cameraAcceleration = 0.05;
  71078. _this.maxCameraSpeed = 20;
  71079. _this.lockedTarget = lockedTarget;
  71080. return _this;
  71081. }
  71082. FollowCamera.prototype.getRadians = function (degrees) {
  71083. return degrees * Math.PI / 180;
  71084. };
  71085. FollowCamera.prototype.follow = function (cameraTarget) {
  71086. if (!cameraTarget)
  71087. return;
  71088. var yRotation;
  71089. if (cameraTarget.rotationQuaternion) {
  71090. var rotMatrix = new BABYLON.Matrix();
  71091. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71092. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71093. }
  71094. else {
  71095. yRotation = cameraTarget.rotation.y;
  71096. }
  71097. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71098. var targetPosition = cameraTarget.getAbsolutePosition();
  71099. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71100. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71101. var dx = targetX - this.position.x;
  71102. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71103. var dz = (targetZ) - this.position.z;
  71104. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71105. var vy = dy * this.cameraAcceleration;
  71106. var vz = dz * this.cameraAcceleration * 2;
  71107. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71108. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71109. }
  71110. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71111. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71112. }
  71113. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71114. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71115. }
  71116. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71117. this.setTarget(targetPosition);
  71118. };
  71119. FollowCamera.prototype._checkInputs = function () {
  71120. _super.prototype._checkInputs.call(this);
  71121. if (this.lockedTarget) {
  71122. this.follow(this.lockedTarget);
  71123. }
  71124. };
  71125. FollowCamera.prototype.getClassName = function () {
  71126. return "FollowCamera";
  71127. };
  71128. __decorate([
  71129. BABYLON.serialize()
  71130. ], FollowCamera.prototype, "radius", void 0);
  71131. __decorate([
  71132. BABYLON.serialize()
  71133. ], FollowCamera.prototype, "rotationOffset", void 0);
  71134. __decorate([
  71135. BABYLON.serialize()
  71136. ], FollowCamera.prototype, "heightOffset", void 0);
  71137. __decorate([
  71138. BABYLON.serialize()
  71139. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71140. __decorate([
  71141. BABYLON.serialize()
  71142. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71143. __decorate([
  71144. BABYLON.serializeAsMeshReference("lockedTargetId")
  71145. ], FollowCamera.prototype, "lockedTarget", void 0);
  71146. return FollowCamera;
  71147. }(BABYLON.TargetCamera));
  71148. BABYLON.FollowCamera = FollowCamera;
  71149. var ArcFollowCamera = /** @class */ (function (_super) {
  71150. __extends(ArcFollowCamera, _super);
  71151. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71152. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71153. _this.alpha = alpha;
  71154. _this.beta = beta;
  71155. _this.radius = radius;
  71156. _this.target = target;
  71157. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71158. _this.follow();
  71159. return _this;
  71160. }
  71161. ArcFollowCamera.prototype.follow = function () {
  71162. if (!this.target) {
  71163. return;
  71164. }
  71165. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71166. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71167. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71168. var targetPosition = this.target.getAbsolutePosition();
  71169. this.position = targetPosition.add(this._cartesianCoordinates);
  71170. this.setTarget(targetPosition);
  71171. };
  71172. ArcFollowCamera.prototype._checkInputs = function () {
  71173. _super.prototype._checkInputs.call(this);
  71174. this.follow();
  71175. };
  71176. ArcFollowCamera.prototype.getClassName = function () {
  71177. return "ArcFollowCamera";
  71178. };
  71179. return ArcFollowCamera;
  71180. }(BABYLON.TargetCamera));
  71181. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71182. })(BABYLON || (BABYLON = {}));
  71183. //# sourceMappingURL=babylon.followCamera.js.map
  71184. "use strict";
  71185. var BABYLON;
  71186. (function (BABYLON) {
  71187. // We're mainly based on the logic defined into the FreeCamera code
  71188. var UniversalCamera = /** @class */ (function (_super) {
  71189. __extends(UniversalCamera, _super);
  71190. //-- end properties for backward compatibility for inputs
  71191. function UniversalCamera(name, position, scene) {
  71192. var _this = _super.call(this, name, position, scene) || this;
  71193. _this.inputs.addGamepad();
  71194. return _this;
  71195. }
  71196. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71197. //-- Begin properties for backward compatibility for inputs
  71198. get: function () {
  71199. var gamepad = this.inputs.attached["gamepad"];
  71200. if (gamepad)
  71201. return gamepad.gamepadAngularSensibility;
  71202. return 0;
  71203. },
  71204. set: function (value) {
  71205. var gamepad = this.inputs.attached["gamepad"];
  71206. if (gamepad)
  71207. gamepad.gamepadAngularSensibility = value;
  71208. },
  71209. enumerable: true,
  71210. configurable: true
  71211. });
  71212. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71213. get: function () {
  71214. var gamepad = this.inputs.attached["gamepad"];
  71215. if (gamepad)
  71216. return gamepad.gamepadMoveSensibility;
  71217. return 0;
  71218. },
  71219. set: function (value) {
  71220. var gamepad = this.inputs.attached["gamepad"];
  71221. if (gamepad)
  71222. gamepad.gamepadMoveSensibility = value;
  71223. },
  71224. enumerable: true,
  71225. configurable: true
  71226. });
  71227. UniversalCamera.prototype.getClassName = function () {
  71228. return "UniversalCamera";
  71229. };
  71230. return UniversalCamera;
  71231. }(BABYLON.TouchCamera));
  71232. BABYLON.UniversalCamera = UniversalCamera;
  71233. })(BABYLON || (BABYLON = {}));
  71234. //# sourceMappingURL=babylon.universalCamera.js.map
  71235. "use strict";
  71236. var BABYLON;
  71237. (function (BABYLON) {
  71238. // We're mainly based on the logic defined into the FreeCamera code
  71239. var GamepadCamera = /** @class */ (function (_super) {
  71240. __extends(GamepadCamera, _super);
  71241. //-- end properties for backward compatibility for inputs
  71242. function GamepadCamera(name, position, scene) {
  71243. return _super.call(this, name, position, scene) || this;
  71244. }
  71245. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71246. //-- Begin properties for backward compatibility for inputs
  71247. get: function () {
  71248. var gamepad = this.inputs.attached["gamepad"];
  71249. if (gamepad)
  71250. return gamepad.gamepadAngularSensibility;
  71251. return 0;
  71252. },
  71253. set: function (value) {
  71254. var gamepad = this.inputs.attached["gamepad"];
  71255. if (gamepad)
  71256. gamepad.gamepadAngularSensibility = value;
  71257. },
  71258. enumerable: true,
  71259. configurable: true
  71260. });
  71261. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71262. get: function () {
  71263. var gamepad = this.inputs.attached["gamepad"];
  71264. if (gamepad)
  71265. return gamepad.gamepadMoveSensibility;
  71266. return 0;
  71267. },
  71268. set: function (value) {
  71269. var gamepad = this.inputs.attached["gamepad"];
  71270. if (gamepad)
  71271. gamepad.gamepadMoveSensibility = value;
  71272. },
  71273. enumerable: true,
  71274. configurable: true
  71275. });
  71276. GamepadCamera.prototype.getClassName = function () {
  71277. return "GamepadCamera";
  71278. };
  71279. return GamepadCamera;
  71280. }(BABYLON.UniversalCamera));
  71281. BABYLON.GamepadCamera = GamepadCamera;
  71282. })(BABYLON || (BABYLON = {}));
  71283. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71284. "use strict";
  71285. var BABYLON;
  71286. (function (BABYLON) {
  71287. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71288. function PostProcessRenderPipelineManager() {
  71289. this._renderPipelines = {};
  71290. }
  71291. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71292. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71293. };
  71294. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71295. if (unique === void 0) { unique = false; }
  71296. var renderPipeline = this._renderPipelines[renderPipelineName];
  71297. if (!renderPipeline) {
  71298. return;
  71299. }
  71300. renderPipeline._attachCameras(cameras, unique);
  71301. };
  71302. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71303. var renderPipeline = this._renderPipelines[renderPipelineName];
  71304. if (!renderPipeline) {
  71305. return;
  71306. }
  71307. renderPipeline._detachCameras(cameras);
  71308. };
  71309. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71310. var renderPipeline = this._renderPipelines[renderPipelineName];
  71311. if (!renderPipeline) {
  71312. return;
  71313. }
  71314. renderPipeline._enableEffect(renderEffectName, cameras);
  71315. };
  71316. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71317. var renderPipeline = this._renderPipelines[renderPipelineName];
  71318. if (!renderPipeline) {
  71319. return;
  71320. }
  71321. renderPipeline._disableEffect(renderEffectName, cameras);
  71322. };
  71323. PostProcessRenderPipelineManager.prototype.update = function () {
  71324. for (var renderPipelineName in this._renderPipelines) {
  71325. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71326. var pipeline = this._renderPipelines[renderPipelineName];
  71327. if (!pipeline.isSupported) {
  71328. pipeline.dispose();
  71329. delete this._renderPipelines[renderPipelineName];
  71330. }
  71331. else {
  71332. pipeline._update();
  71333. }
  71334. }
  71335. }
  71336. };
  71337. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71338. for (var renderPipelineName in this._renderPipelines) {
  71339. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71340. var pipeline = this._renderPipelines[renderPipelineName];
  71341. pipeline._rebuild();
  71342. }
  71343. }
  71344. };
  71345. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71346. for (var renderPipelineName in this._renderPipelines) {
  71347. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71348. var pipeline = this._renderPipelines[renderPipelineName];
  71349. pipeline.dispose();
  71350. }
  71351. }
  71352. };
  71353. return PostProcessRenderPipelineManager;
  71354. }());
  71355. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71356. })(BABYLON || (BABYLON = {}));
  71357. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71358. "use strict";
  71359. var BABYLON;
  71360. (function (BABYLON) {
  71361. /**
  71362. * This represents a set of one or more post processes in Babylon.
  71363. * A post process can be used to apply a shader to a texture after it is rendered.
  71364. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71365. */
  71366. var PostProcessRenderEffect = /** @class */ (function () {
  71367. /**
  71368. * Instantiates a post process render effect.
  71369. * A post process can be used to apply a shader to a texture after it is rendered.
  71370. * @param engine The engine the effect is tied to
  71371. * @param name The name of the effect
  71372. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71373. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71374. */
  71375. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71376. this._name = name;
  71377. this._singleInstance = singleInstance || true;
  71378. this._getPostProcesses = getPostProcesses;
  71379. this._cameras = {};
  71380. this._indicesForCamera = {};
  71381. this._postProcesses = {};
  71382. }
  71383. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71384. /**
  71385. * Checks if all the post processes in the effect are supported.
  71386. */
  71387. get: function () {
  71388. for (var index in this._postProcesses) {
  71389. if (this._postProcesses.hasOwnProperty(index)) {
  71390. var pps = this._postProcesses[index];
  71391. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71392. if (!pps[ppIndex].isSupported) {
  71393. return false;
  71394. }
  71395. }
  71396. }
  71397. }
  71398. return true;
  71399. },
  71400. enumerable: true,
  71401. configurable: true
  71402. });
  71403. /**
  71404. * Updates the current state of the effect
  71405. */
  71406. PostProcessRenderEffect.prototype._update = function () {
  71407. };
  71408. /**
  71409. * Attaches the effect on cameras
  71410. * @param cameras The camera to attach to.
  71411. */
  71412. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71413. var _this = this;
  71414. var cameraKey;
  71415. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71416. if (!cams) {
  71417. return;
  71418. }
  71419. for (var i = 0; i < cams.length; i++) {
  71420. var camera = cams[i];
  71421. var cameraName = camera.name;
  71422. if (this._singleInstance) {
  71423. cameraKey = 0;
  71424. }
  71425. else {
  71426. cameraKey = cameraName;
  71427. }
  71428. if (!this._postProcesses[cameraKey]) {
  71429. var postProcess = this._getPostProcesses();
  71430. if (postProcess) {
  71431. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71432. }
  71433. }
  71434. if (!this._indicesForCamera[cameraName]) {
  71435. this._indicesForCamera[cameraName] = [];
  71436. }
  71437. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71438. var index = camera.attachPostProcess(postProcess);
  71439. _this._indicesForCamera[cameraName].push(index);
  71440. });
  71441. if (!this._cameras[cameraName]) {
  71442. this._cameras[cameraName] = camera;
  71443. }
  71444. }
  71445. };
  71446. /**
  71447. * Detatches the effect on cameras
  71448. * @param cameras The camera to detatch from.
  71449. */
  71450. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71451. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71452. if (!cams) {
  71453. return;
  71454. }
  71455. for (var i = 0; i < cams.length; i++) {
  71456. var camera = cams[i];
  71457. var cameraName = camera.name;
  71458. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71459. camera.detachPostProcess(postProcess);
  71460. });
  71461. if (this._cameras[cameraName]) {
  71462. //this._indicesForCamera.splice(index, 1);
  71463. this._cameras[cameraName] = null;
  71464. }
  71465. }
  71466. };
  71467. /**
  71468. * Enables the effect on given cameras
  71469. * @param cameras The camera to enable.
  71470. */
  71471. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71472. var _this = this;
  71473. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71474. if (!cams) {
  71475. return;
  71476. }
  71477. for (var i = 0; i < cams.length; i++) {
  71478. var camera = cams[i];
  71479. var cameraName = camera.name;
  71480. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71481. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71482. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71483. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71484. });
  71485. }
  71486. }
  71487. }
  71488. };
  71489. /**
  71490. * Disables the effect on the given cameras
  71491. * @param cameras The camera to disable.
  71492. */
  71493. PostProcessRenderEffect.prototype._disable = function (cameras) {
  71494. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71495. if (!cams) {
  71496. return;
  71497. }
  71498. for (var i = 0; i < cams.length; i++) {
  71499. var camera = cams[i];
  71500. var cameraName = camera.name;
  71501. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71502. camera.detachPostProcess(postProcess);
  71503. });
  71504. }
  71505. };
  71506. /**
  71507. * Gets a list of the post processes contained in the effect.
  71508. * @param camera The camera to get the post processes on.
  71509. * @returns The list of the post processes in the effect.
  71510. */
  71511. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  71512. if (this._singleInstance) {
  71513. return this._postProcesses[0];
  71514. }
  71515. else {
  71516. if (!camera) {
  71517. return null;
  71518. }
  71519. return this._postProcesses[camera.name];
  71520. }
  71521. };
  71522. return PostProcessRenderEffect;
  71523. }());
  71524. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  71525. })(BABYLON || (BABYLON = {}));
  71526. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  71527. "use strict";
  71528. var BABYLON;
  71529. (function (BABYLON) {
  71530. var PostProcessRenderPipeline = /** @class */ (function () {
  71531. function PostProcessRenderPipeline(engine, name) {
  71532. this.engine = engine;
  71533. this._name = name;
  71534. this._renderEffects = {};
  71535. this._renderEffectsForIsolatedPass = new Array();
  71536. this._cameras = [];
  71537. }
  71538. PostProcessRenderPipeline.prototype.getClassName = function () {
  71539. return "PostProcessRenderPipeline";
  71540. };
  71541. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  71542. get: function () {
  71543. for (var renderEffectName in this._renderEffects) {
  71544. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71545. if (!this._renderEffects[renderEffectName].isSupported) {
  71546. return false;
  71547. }
  71548. }
  71549. }
  71550. return true;
  71551. },
  71552. enumerable: true,
  71553. configurable: true
  71554. });
  71555. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  71556. this._renderEffects[renderEffect._name] = renderEffect;
  71557. };
  71558. // private
  71559. PostProcessRenderPipeline.prototype._rebuild = function () {
  71560. };
  71561. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  71562. var renderEffects = this._renderEffects[renderEffectName];
  71563. if (!renderEffects) {
  71564. return;
  71565. }
  71566. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71567. };
  71568. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71569. var renderEffects = this._renderEffects[renderEffectName];
  71570. if (!renderEffects) {
  71571. return;
  71572. }
  71573. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71574. };
  71575. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71576. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71577. if (!cams) {
  71578. return;
  71579. }
  71580. var indicesToDelete = [];
  71581. var i;
  71582. for (i = 0; i < cams.length; i++) {
  71583. var camera = cams[i];
  71584. var cameraName = camera.name;
  71585. if (this._cameras.indexOf(camera) === -1) {
  71586. this._cameras[cameraName] = camera;
  71587. }
  71588. else if (unique) {
  71589. indicesToDelete.push(i);
  71590. }
  71591. }
  71592. for (i = 0; i < indicesToDelete.length; i++) {
  71593. cameras.splice(indicesToDelete[i], 1);
  71594. }
  71595. for (var renderEffectName in this._renderEffects) {
  71596. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71597. this._renderEffects[renderEffectName]._attachCameras(cams);
  71598. }
  71599. }
  71600. };
  71601. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71602. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71603. if (!cams) {
  71604. return;
  71605. }
  71606. for (var renderEffectName in this._renderEffects) {
  71607. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71608. this._renderEffects[renderEffectName]._detachCameras(cams);
  71609. }
  71610. }
  71611. for (var i = 0; i < cams.length; i++) {
  71612. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71613. }
  71614. };
  71615. PostProcessRenderPipeline.prototype._update = function () {
  71616. for (var renderEffectName in this._renderEffects) {
  71617. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71618. this._renderEffects[renderEffectName]._update();
  71619. }
  71620. }
  71621. for (var i = 0; i < this._cameras.length; i++) {
  71622. var cameraName = this._cameras[i].name;
  71623. if (this._renderEffectsForIsolatedPass[cameraName]) {
  71624. this._renderEffectsForIsolatedPass[cameraName]._update();
  71625. }
  71626. }
  71627. };
  71628. PostProcessRenderPipeline.prototype._reset = function () {
  71629. this._renderEffects = {};
  71630. this._renderEffectsForIsolatedPass = new Array();
  71631. };
  71632. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  71633. // 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)
  71634. var effectKeys = Object.keys(this._renderEffects);
  71635. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  71636. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  71637. if (postProcesses) {
  71638. postProcesses[0].samples = sampleCount;
  71639. return true;
  71640. }
  71641. }
  71642. return false;
  71643. };
  71644. PostProcessRenderPipeline.prototype.dispose = function () {
  71645. // Must be implemented by children
  71646. };
  71647. __decorate([
  71648. BABYLON.serialize()
  71649. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  71650. return PostProcessRenderPipeline;
  71651. }());
  71652. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  71653. })(BABYLON || (BABYLON = {}));
  71654. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  71655. "use strict";
  71656. var BABYLON;
  71657. (function (BABYLON) {
  71658. /**
  71659. * This represents a depth renderer in Babylon.
  71660. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  71661. */
  71662. var DepthRenderer = /** @class */ (function () {
  71663. /**
  71664. * Instantiates a depth renderer
  71665. * @param scene The scene the renderer belongs to
  71666. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  71667. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  71668. */
  71669. function DepthRenderer(scene, type, camera) {
  71670. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71671. if (camera === void 0) { camera = null; }
  71672. var _this = this;
  71673. this._scene = scene;
  71674. this._camera = camera;
  71675. var engine = scene.getEngine();
  71676. // Render target
  71677. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  71678. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71679. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71680. this._depthMap.refreshRate = 1;
  71681. this._depthMap.renderParticles = false;
  71682. this._depthMap.renderList = null;
  71683. // Camera to get depth map from to support multiple concurrent cameras
  71684. this._depthMap.activeCamera = this._camera;
  71685. this._depthMap.ignoreCameraViewport = true;
  71686. this._depthMap.useCameraPostProcesses = false;
  71687. // set default depth value to 1.0 (far away)
  71688. this._depthMap.onClearObservable.add(function (engine) {
  71689. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  71690. });
  71691. // Custom render function
  71692. var renderSubMesh = function (subMesh) {
  71693. var mesh = subMesh.getRenderingMesh();
  71694. var scene = _this._scene;
  71695. var engine = scene.getEngine();
  71696. var material = subMesh.getMaterial();
  71697. if (!material) {
  71698. return;
  71699. }
  71700. // Culling and reverse (right handed system)
  71701. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71702. // Managing instances
  71703. var batch = mesh._getInstancesRenderList(subMesh._id);
  71704. if (batch.mustReturn) {
  71705. return;
  71706. }
  71707. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71708. var camera = _this._camera || scene.activeCamera;
  71709. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  71710. engine.enableEffect(_this._effect);
  71711. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71712. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71713. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  71714. // Alpha test
  71715. if (material && material.needAlphaTesting()) {
  71716. var alphaTexture = material.getAlphaTestTexture();
  71717. if (alphaTexture) {
  71718. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71719. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71720. }
  71721. }
  71722. // Bones
  71723. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71724. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71725. }
  71726. // Draw
  71727. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71728. }
  71729. };
  71730. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71731. var index;
  71732. if (depthOnlySubMeshes.length) {
  71733. engine.setColorWrite(false);
  71734. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71735. renderSubMesh(depthOnlySubMeshes.data[index]);
  71736. }
  71737. engine.setColorWrite(true);
  71738. }
  71739. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71740. renderSubMesh(opaqueSubMeshes.data[index]);
  71741. }
  71742. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71743. renderSubMesh(alphaTestSubMeshes.data[index]);
  71744. }
  71745. };
  71746. }
  71747. /**
  71748. * Creates the depth rendering effect and checks if the effect is ready.
  71749. * @param subMesh The submesh to be used to render the depth map of
  71750. * @param useInstances If multiple world instances should be used
  71751. * @returns if the depth renderer is ready to render the depth map
  71752. */
  71753. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  71754. var material = subMesh.getMaterial();
  71755. if (material.disableDepthWrite) {
  71756. return false;
  71757. }
  71758. var defines = [];
  71759. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71760. var mesh = subMesh.getMesh();
  71761. // Alpha test
  71762. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  71763. defines.push("#define ALPHATEST");
  71764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71765. attribs.push(BABYLON.VertexBuffer.UVKind);
  71766. defines.push("#define UV1");
  71767. }
  71768. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71769. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71770. defines.push("#define UV2");
  71771. }
  71772. }
  71773. // Bones
  71774. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71775. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71776. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71777. if (mesh.numBoneInfluencers > 4) {
  71778. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71779. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71780. }
  71781. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71782. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71783. }
  71784. else {
  71785. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71786. }
  71787. // Instances
  71788. if (useInstances) {
  71789. defines.push("#define INSTANCES");
  71790. attribs.push("world0");
  71791. attribs.push("world1");
  71792. attribs.push("world2");
  71793. attribs.push("world3");
  71794. }
  71795. // Get correct effect
  71796. var join = defines.join("\n");
  71797. if (this._cachedDefines !== join) {
  71798. this._cachedDefines = join;
  71799. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  71800. }
  71801. return this._effect.isReady();
  71802. };
  71803. /**
  71804. * Gets the texture which the depth map will be written to.
  71805. * @returns The depth map texture
  71806. */
  71807. DepthRenderer.prototype.getDepthMap = function () {
  71808. return this._depthMap;
  71809. };
  71810. /**
  71811. * Disposes of the depth renderer.
  71812. */
  71813. DepthRenderer.prototype.dispose = function () {
  71814. this._depthMap.dispose();
  71815. };
  71816. return DepthRenderer;
  71817. }());
  71818. BABYLON.DepthRenderer = DepthRenderer;
  71819. })(BABYLON || (BABYLON = {}));
  71820. //# sourceMappingURL=babylon.depthRenderer.js.map
  71821. "use strict";
  71822. var BABYLON;
  71823. (function (BABYLON) {
  71824. var SSAORenderingPipeline = /** @class */ (function (_super) {
  71825. __extends(SSAORenderingPipeline, _super);
  71826. /**
  71827. * @constructor
  71828. * @param {string} name - The rendering pipeline name
  71829. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71830. * @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 }
  71831. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71832. */
  71833. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  71834. var _this = _super.call(this, scene.getEngine(), name) || this;
  71835. // Members
  71836. /**
  71837. * The PassPostProcess id in the pipeline that contains the original scene color
  71838. */
  71839. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71840. /**
  71841. * The SSAO PostProcess id in the pipeline
  71842. */
  71843. _this.SSAORenderEffect = "SSAORenderEffect";
  71844. /**
  71845. * The horizontal blur PostProcess id in the pipeline
  71846. */
  71847. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71848. /**
  71849. * The vertical blur PostProcess id in the pipeline
  71850. */
  71851. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71852. /**
  71853. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71854. */
  71855. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71856. /**
  71857. * The output strength of the SSAO post-process. Default value is 1.0.
  71858. */
  71859. _this.totalStrength = 1.0;
  71860. /**
  71861. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  71862. */
  71863. _this.radius = 0.0001;
  71864. /**
  71865. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  71866. * Must not be equal to fallOff and superior to fallOff.
  71867. * Default value is 0.975
  71868. */
  71869. _this.area = 0.0075;
  71870. /**
  71871. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  71872. * Must not be equal to area and inferior to area.
  71873. * Default value is 0.0
  71874. */
  71875. _this.fallOff = 0.000001;
  71876. /**
  71877. * The base color of the SSAO post-process
  71878. * The final result is "base + ssao" between [0, 1]
  71879. */
  71880. _this.base = 0.5;
  71881. _this._firstUpdate = true;
  71882. _this._scene = scene;
  71883. // Set up assets
  71884. _this._createRandomTexture();
  71885. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71886. var ssaoRatio = ratio.ssaoRatio || ratio;
  71887. var combineRatio = ratio.combineRatio || ratio;
  71888. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71889. _this._createSSAOPostProcess(ssaoRatio);
  71890. _this._createBlurPostProcess(ssaoRatio);
  71891. _this._createSSAOCombinePostProcess(combineRatio);
  71892. // Set up pipeline
  71893. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71894. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71895. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71896. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71897. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71898. // Finish
  71899. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71900. if (cameras)
  71901. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71902. return _this;
  71903. }
  71904. // Public Methods
  71905. /**
  71906. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71907. */
  71908. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71909. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71910. for (var i = 0; i < this._scene.cameras.length; i++) {
  71911. var camera = this._scene.cameras[i];
  71912. this._originalColorPostProcess.dispose(camera);
  71913. this._ssaoPostProcess.dispose(camera);
  71914. this._blurHPostProcess.dispose(camera);
  71915. this._blurVPostProcess.dispose(camera);
  71916. this._ssaoCombinePostProcess.dispose(camera);
  71917. }
  71918. this._randomTexture.dispose();
  71919. if (disableDepthRender)
  71920. this._scene.disableDepthRenderer();
  71921. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71922. _super.prototype.dispose.call(this);
  71923. };
  71924. // Private Methods
  71925. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  71926. var _this = this;
  71927. var size = 16;
  71928. 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);
  71929. 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);
  71930. this._blurHPostProcess.onActivateObservable.add(function () {
  71931. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  71932. _this._blurHPostProcess.kernel = size * dw;
  71933. });
  71934. this._blurVPostProcess.onActivateObservable.add(function () {
  71935. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  71936. _this._blurVPostProcess.kernel = size * dw;
  71937. });
  71938. };
  71939. SSAORenderingPipeline.prototype._rebuild = function () {
  71940. this._firstUpdate = true;
  71941. _super.prototype._rebuild.call(this);
  71942. };
  71943. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71944. var _this = this;
  71945. var numSamples = 16;
  71946. var sampleSphere = [
  71947. 0.5381, 0.1856, -0.4319,
  71948. 0.1379, 0.2486, 0.4430,
  71949. 0.3371, 0.5679, -0.0057,
  71950. -0.6999, -0.0451, -0.0019,
  71951. 0.0689, -0.1598, -0.8547,
  71952. 0.0560, 0.0069, -0.1843,
  71953. -0.0146, 0.1402, 0.0762,
  71954. 0.0100, -0.1924, -0.0344,
  71955. -0.3577, -0.5301, -0.4358,
  71956. -0.3169, 0.1063, 0.0158,
  71957. 0.0103, -0.5869, 0.0046,
  71958. -0.0897, -0.4940, 0.3287,
  71959. 0.7119, -0.0154, -0.0918,
  71960. -0.0533, 0.0596, -0.5411,
  71961. 0.0352, -0.0631, 0.5460,
  71962. -0.4776, 0.2847, -0.0271
  71963. ];
  71964. var samplesFactor = 1.0 / numSamples;
  71965. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  71966. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71967. "area", "fallOff", "base", "range", "viewport"
  71968. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71969. this._ssaoPostProcess.onApply = function (effect) {
  71970. if (_this._firstUpdate) {
  71971. effect.setArray3("sampleSphere", sampleSphere);
  71972. effect.setFloat("samplesFactor", samplesFactor);
  71973. effect.setFloat("randTextureTiles", 4.0);
  71974. }
  71975. effect.setFloat("totalStrength", _this.totalStrength);
  71976. effect.setFloat("radius", _this.radius);
  71977. effect.setFloat("area", _this.area);
  71978. effect.setFloat("fallOff", _this.fallOff);
  71979. effect.setFloat("base", _this.base);
  71980. effect.setTexture("textureSampler", _this._depthTexture);
  71981. effect.setTexture("randomSampler", _this._randomTexture);
  71982. };
  71983. };
  71984. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71985. var _this = this;
  71986. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71987. this._ssaoCombinePostProcess.onApply = function (effect) {
  71988. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71989. };
  71990. };
  71991. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  71992. var size = 512;
  71993. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71994. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71995. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71996. var context = this._randomTexture.getContext();
  71997. var rand = function (min, max) {
  71998. return Math.random() * (max - min) + min;
  71999. };
  72000. var randVector = BABYLON.Vector3.Zero();
  72001. for (var x = 0; x < size; x++) {
  72002. for (var y = 0; y < size; y++) {
  72003. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72004. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72005. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72006. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72007. context.fillRect(x, y, 1, 1);
  72008. }
  72009. }
  72010. this._randomTexture.update(false);
  72011. };
  72012. __decorate([
  72013. BABYLON.serialize()
  72014. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72015. __decorate([
  72016. BABYLON.serialize()
  72017. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72018. __decorate([
  72019. BABYLON.serialize()
  72020. ], SSAORenderingPipeline.prototype, "area", void 0);
  72021. __decorate([
  72022. BABYLON.serialize()
  72023. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72024. __decorate([
  72025. BABYLON.serialize()
  72026. ], SSAORenderingPipeline.prototype, "base", void 0);
  72027. return SSAORenderingPipeline;
  72028. }(BABYLON.PostProcessRenderPipeline));
  72029. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72030. })(BABYLON || (BABYLON = {}));
  72031. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72032. "use strict";
  72033. var BABYLON;
  72034. (function (BABYLON) {
  72035. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72036. __extends(SSAO2RenderingPipeline, _super);
  72037. /**
  72038. * @constructor
  72039. * @param {string} name - The rendering pipeline name
  72040. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72041. * @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 }
  72042. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72043. */
  72044. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72045. var _this = _super.call(this, scene.getEngine(), name) || this;
  72046. // Members
  72047. /**
  72048. * The PassPostProcess id in the pipeline that contains the original scene color
  72049. */
  72050. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72051. /**
  72052. * The SSAO PostProcess id in the pipeline
  72053. */
  72054. _this.SSAORenderEffect = "SSAORenderEffect";
  72055. /**
  72056. * The horizontal blur PostProcess id in the pipeline
  72057. */
  72058. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72059. /**
  72060. * The vertical blur PostProcess id in the pipeline
  72061. */
  72062. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72063. /**
  72064. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72065. */
  72066. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72067. /**
  72068. * The output strength of the SSAO post-process. Default value is 1.0.
  72069. */
  72070. _this.totalStrength = 1.0;
  72071. /**
  72072. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72073. */
  72074. _this.maxZ = 100.0;
  72075. /**
  72076. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72077. */
  72078. _this.minZAspect = 0.2;
  72079. /**
  72080. * Number of samples used for the SSAO calculations. Default value is 8
  72081. */
  72082. _this._samples = 8;
  72083. /**
  72084. * Are we using bilateral blur ?
  72085. */
  72086. _this._expensiveBlur = true;
  72087. /**
  72088. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72089. */
  72090. _this.radius = 2.0;
  72091. /**
  72092. * The base color of the SSAO post-process
  72093. * The final result is "base + ssao" between [0, 1]
  72094. */
  72095. _this.base = 0.1;
  72096. _this._firstUpdate = true;
  72097. _this._scene = scene;
  72098. if (!_this.isSupported) {
  72099. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72100. return _this;
  72101. }
  72102. var ssaoRatio = ratio.ssaoRatio || ratio;
  72103. var blurRatio = ratio.blurRatio || ratio;
  72104. // Set up assets
  72105. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72106. _this._createRandomTexture();
  72107. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72108. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72109. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72110. _this._createSSAOPostProcess(1.0);
  72111. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72112. _this._createSSAOCombinePostProcess(blurRatio);
  72113. // Set up pipeline
  72114. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72115. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72117. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72118. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72119. // Finish
  72120. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72121. if (cameras)
  72122. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72123. return _this;
  72124. }
  72125. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72126. get: function () {
  72127. return this._samples;
  72128. },
  72129. set: function (n) {
  72130. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72131. this._samples = n;
  72132. this._sampleSphere = this._generateHemisphere();
  72133. this._firstUpdate = true;
  72134. },
  72135. enumerable: true,
  72136. configurable: true
  72137. });
  72138. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72139. get: function () {
  72140. return this._expensiveBlur;
  72141. },
  72142. set: function (b) {
  72143. 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"]);
  72144. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72145. this._expensiveBlur = b;
  72146. this._firstUpdate = true;
  72147. },
  72148. enumerable: true,
  72149. configurable: true
  72150. });
  72151. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72152. /**
  72153. * Support test.
  72154. */
  72155. get: function () {
  72156. var engine = BABYLON.Engine.LastCreatedEngine;
  72157. if (!engine) {
  72158. return false;
  72159. }
  72160. return engine.getCaps().drawBuffersExtension;
  72161. },
  72162. enumerable: true,
  72163. configurable: true
  72164. });
  72165. // Public Methods
  72166. /**
  72167. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72168. */
  72169. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72170. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72171. for (var i = 0; i < this._scene.cameras.length; i++) {
  72172. var camera = this._scene.cameras[i];
  72173. this._originalColorPostProcess.dispose(camera);
  72174. this._ssaoPostProcess.dispose(camera);
  72175. this._blurHPostProcess.dispose(camera);
  72176. this._blurVPostProcess.dispose(camera);
  72177. this._ssaoCombinePostProcess.dispose(camera);
  72178. }
  72179. this._randomTexture.dispose();
  72180. if (disableGeometryBufferRenderer)
  72181. this._scene.disableGeometryBufferRenderer();
  72182. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72183. _super.prototype.dispose.call(this);
  72184. };
  72185. // Private Methods
  72186. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72187. var _this = this;
  72188. this._samplerOffsets = [];
  72189. var expensive = this.expensiveBlur;
  72190. for (var i = -8; i < 8; i++) {
  72191. this._samplerOffsets.push(i * 2 + 0.5);
  72192. }
  72193. 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");
  72194. this._blurHPostProcess.onApply = function (effect) {
  72195. if (!_this._scene.activeCamera) {
  72196. return;
  72197. }
  72198. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72199. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72200. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72201. effect.setFloat("radius", _this.radius);
  72202. effect.setTexture("depthSampler", _this._depthTexture);
  72203. if (_this._firstUpdate) {
  72204. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72205. }
  72206. };
  72207. 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");
  72208. this._blurVPostProcess.onApply = function (effect) {
  72209. if (!_this._scene.activeCamera) {
  72210. return;
  72211. }
  72212. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72213. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72214. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72215. effect.setFloat("radius", _this.radius);
  72216. effect.setTexture("depthSampler", _this._depthTexture);
  72217. if (_this._firstUpdate) {
  72218. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72219. _this._firstUpdate = false;
  72220. }
  72221. };
  72222. };
  72223. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72224. this._firstUpdate = true;
  72225. _super.prototype._rebuild.call(this);
  72226. };
  72227. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72228. var numSamples = this.samples;
  72229. var result = [];
  72230. var vector, scale;
  72231. var rand = function (min, max) {
  72232. return Math.random() * (max - min) + min;
  72233. };
  72234. var i = 0;
  72235. while (i < numSamples) {
  72236. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72237. vector.normalize();
  72238. scale = i / numSamples;
  72239. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72240. vector.scaleInPlace(scale);
  72241. result.push(vector.x, vector.y, vector.z);
  72242. i++;
  72243. }
  72244. return result;
  72245. };
  72246. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72247. var _this = this;
  72248. var numSamples = this.samples;
  72249. this._sampleSphere = this._generateHemisphere();
  72250. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72251. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72252. "base", "range", "projection", "near", "far", "texelSize",
  72253. "xViewport", "yViewport", "maxZ", "minZAspect"
  72254. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72255. this._ssaoPostProcess.onApply = function (effect) {
  72256. if (_this._firstUpdate) {
  72257. effect.setArray3("sampleSphere", _this._sampleSphere);
  72258. effect.setFloat("randTextureTiles", 4.0);
  72259. }
  72260. if (!_this._scene.activeCamera) {
  72261. return;
  72262. }
  72263. effect.setFloat("samplesFactor", 1 / _this.samples);
  72264. effect.setFloat("totalStrength", _this.totalStrength);
  72265. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72266. effect.setFloat("radius", _this.radius);
  72267. effect.setFloat("maxZ", _this.maxZ);
  72268. effect.setFloat("minZAspect", _this.minZAspect);
  72269. effect.setFloat("base", _this.base);
  72270. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72271. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72272. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72273. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72274. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72275. effect.setTexture("textureSampler", _this._depthTexture);
  72276. effect.setTexture("normalSampler", _this._normalTexture);
  72277. effect.setTexture("randomSampler", _this._randomTexture);
  72278. };
  72279. };
  72280. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72281. var _this = this;
  72282. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72283. this._ssaoCombinePostProcess.onApply = function (effect) {
  72284. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72285. };
  72286. };
  72287. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72288. var size = 512;
  72289. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72290. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72291. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72292. var context = this._randomTexture.getContext();
  72293. var rand = function (min, max) {
  72294. return Math.random() * (max - min) + min;
  72295. };
  72296. var randVector = BABYLON.Vector3.Zero();
  72297. for (var x = 0; x < size; x++) {
  72298. for (var y = 0; y < size; y++) {
  72299. randVector.x = rand(0.0, 1.0);
  72300. randVector.y = rand(0.0, 1.0);
  72301. randVector.z = 0.0;
  72302. randVector.normalize();
  72303. randVector.scaleInPlace(255);
  72304. randVector.x = Math.floor(randVector.x);
  72305. randVector.y = Math.floor(randVector.y);
  72306. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72307. context.fillRect(x, y, 1, 1);
  72308. }
  72309. }
  72310. this._randomTexture.update(false);
  72311. };
  72312. __decorate([
  72313. BABYLON.serialize()
  72314. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72315. __decorate([
  72316. BABYLON.serialize()
  72317. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72318. __decorate([
  72319. BABYLON.serialize()
  72320. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72321. __decorate([
  72322. BABYLON.serialize("samples")
  72323. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72324. __decorate([
  72325. BABYLON.serialize("expensiveBlur")
  72326. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72327. __decorate([
  72328. BABYLON.serialize()
  72329. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72330. __decorate([
  72331. BABYLON.serialize()
  72332. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72333. return SSAO2RenderingPipeline;
  72334. }(BABYLON.PostProcessRenderPipeline));
  72335. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72336. })(BABYLON || (BABYLON = {}));
  72337. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72338. "use strict";
  72339. // BABYLON.JS Chromatic Aberration GLSL Shader
  72340. // Author: Olivier Guyot
  72341. // Separates very slightly R, G and B colors on the edges of the screen
  72342. // Inspired by Francois Tarlier & Martins Upitis
  72343. var BABYLON;
  72344. (function (BABYLON) {
  72345. var LensRenderingPipeline = /** @class */ (function (_super) {
  72346. __extends(LensRenderingPipeline, _super);
  72347. /**
  72348. * @constructor
  72349. *
  72350. * Effect parameters are as follow:
  72351. * {
  72352. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72353. * edge_blur: number; // from 0 to x (1 for realism)
  72354. * distortion: number; // from 0 to x (1 for realism)
  72355. * grain_amount: number; // from 0 to 1
  72356. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72357. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72358. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72359. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72360. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72361. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72362. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72363. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72364. * }
  72365. * Note: if an effect parameter is unset, effect is disabled
  72366. *
  72367. * @param {string} name - The rendering pipeline name
  72368. * @param {object} parameters - An object containing all parameters (see above)
  72369. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72370. * @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)
  72371. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72372. */
  72373. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72374. if (ratio === void 0) { ratio = 1.0; }
  72375. var _this = _super.call(this, scene.getEngine(), name) || this;
  72376. // Lens effects can be of the following:
  72377. // - chromatic aberration (slight shift of RGB colors)
  72378. // - blur on the edge of the lens
  72379. // - lens distortion
  72380. // - depth-of-field blur & highlights enhancing
  72381. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72382. // - grain effect (noise or custom texture)
  72383. // Two additional texture samplers are needed:
  72384. // - depth map (for depth-of-field)
  72385. // - grain texture
  72386. /**
  72387. * The chromatic aberration PostProcess id in the pipeline
  72388. */
  72389. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72390. /**
  72391. * The highlights enhancing PostProcess id in the pipeline
  72392. */
  72393. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72394. /**
  72395. * The depth-of-field PostProcess id in the pipeline
  72396. */
  72397. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72398. _this._scene = scene;
  72399. // Fetch texture samplers
  72400. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72401. if (parameters.grain_texture) {
  72402. _this._grainTexture = parameters.grain_texture;
  72403. }
  72404. else {
  72405. _this._createGrainTexture();
  72406. }
  72407. // save parameters
  72408. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72409. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72410. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72411. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72412. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72413. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72414. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72415. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72416. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72417. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72418. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72419. // Create effects
  72420. _this._createChromaticAberrationPostProcess(ratio);
  72421. _this._createHighlightsPostProcess(ratio);
  72422. _this._createDepthOfFieldPostProcess(ratio / 4);
  72423. // Set up pipeline
  72424. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72425. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72426. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72427. if (_this._highlightsGain === -1) {
  72428. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72429. }
  72430. // Finish
  72431. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72432. if (cameras) {
  72433. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72434. }
  72435. return _this;
  72436. }
  72437. // public methods (self explanatory)
  72438. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72439. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72440. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72441. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72442. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72443. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72444. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72445. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72446. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72447. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72448. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72449. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72450. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72451. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72452. };
  72453. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72454. this._highlightsPostProcess.updateEffect();
  72455. };
  72456. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72457. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72458. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72459. this._highlightsGain = amount;
  72460. };
  72461. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72462. if (this._highlightsGain === -1) {
  72463. this._highlightsGain = 1.0;
  72464. }
  72465. this._highlightsThreshold = amount;
  72466. };
  72467. LensRenderingPipeline.prototype.disableHighlights = function () {
  72468. this._highlightsGain = -1;
  72469. };
  72470. /**
  72471. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72472. */
  72473. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72474. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72475. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72476. this._chromaticAberrationPostProcess = null;
  72477. this._highlightsPostProcess = null;
  72478. this._depthOfFieldPostProcess = null;
  72479. this._grainTexture.dispose();
  72480. if (disableDepthRender)
  72481. this._scene.disableDepthRenderer();
  72482. };
  72483. // colors shifting and distortion
  72484. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72485. var _this = this;
  72486. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72487. [], // samplers
  72488. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72489. this._chromaticAberrationPostProcess.onApply = function (effect) {
  72490. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  72491. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72492. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72493. effect.setFloat('radialIntensity', 1);
  72494. effect.setFloat2('direction', 17, 17);
  72495. effect.setFloat2('centerPosition', 0.5, 0.5);
  72496. };
  72497. };
  72498. // highlights enhancing
  72499. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  72500. var _this = this;
  72501. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  72502. [], // samplers
  72503. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  72504. this._highlightsPostProcess.onApply = function (effect) {
  72505. effect.setFloat('gain', _this._highlightsGain);
  72506. effect.setFloat('threshold', _this._highlightsThreshold);
  72507. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  72508. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72509. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72510. };
  72511. };
  72512. // colors shifting and distortion
  72513. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  72514. var _this = this;
  72515. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  72516. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  72517. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  72518. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72519. this._depthOfFieldPostProcess.onApply = function (effect) {
  72520. effect.setTexture("depthSampler", _this._depthTexture);
  72521. effect.setTexture("grainSampler", _this._grainTexture);
  72522. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  72523. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  72524. effect.setFloat('grain_amount', _this._grainAmount);
  72525. effect.setBool('blur_noise', _this._blurNoise);
  72526. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72527. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72528. effect.setFloat('distortion', _this._distortion);
  72529. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  72530. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  72531. effect.setFloat('aperture', _this._dofAperture);
  72532. effect.setFloat('darken', _this._dofDarken);
  72533. effect.setFloat('edge_blur', _this._edgeBlur);
  72534. effect.setBool('highlights', (_this._highlightsGain !== -1));
  72535. if (_this._scene.activeCamera) {
  72536. effect.setFloat('near', _this._scene.activeCamera.minZ);
  72537. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  72538. }
  72539. };
  72540. };
  72541. // creates a black and white random noise texture, 512x512
  72542. LensRenderingPipeline.prototype._createGrainTexture = function () {
  72543. var size = 512;
  72544. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72545. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72546. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72547. var context = this._grainTexture.getContext();
  72548. var rand = function (min, max) {
  72549. return Math.random() * (max - min) + min;
  72550. };
  72551. var value;
  72552. for (var x = 0; x < size; x++) {
  72553. for (var y = 0; y < size; y++) {
  72554. value = Math.floor(rand(0.42, 0.58) * 255);
  72555. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  72556. context.fillRect(x, y, 1, 1);
  72557. }
  72558. }
  72559. this._grainTexture.update(false);
  72560. };
  72561. return LensRenderingPipeline;
  72562. }(BABYLON.PostProcessRenderPipeline));
  72563. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72564. })(BABYLON || (BABYLON = {}));
  72565. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72566. "use strict";
  72567. var BABYLON;
  72568. (function (BABYLON) {
  72569. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72570. __extends(StandardRenderingPipeline, _super);
  72571. /**
  72572. * @constructor
  72573. * @param {string} name - The rendering pipeline name
  72574. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72575. * @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)
  72576. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72577. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72578. */
  72579. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72580. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72581. var _this = _super.call(this, scene.getEngine(), name) || this;
  72582. _this.downSampleX4PostProcess = null;
  72583. _this.brightPassPostProcess = null;
  72584. _this.blurHPostProcesses = [];
  72585. _this.blurVPostProcesses = [];
  72586. _this.textureAdderPostProcess = null;
  72587. _this.volumetricLightPostProcess = null;
  72588. _this.volumetricLightSmoothXPostProcess = null;
  72589. _this.volumetricLightSmoothYPostProcess = null;
  72590. _this.volumetricLightMergePostProces = null;
  72591. _this.volumetricLightFinalPostProcess = null;
  72592. _this.luminancePostProcess = null;
  72593. _this.luminanceDownSamplePostProcesses = [];
  72594. _this.hdrPostProcess = null;
  72595. _this.textureAdderFinalPostProcess = null;
  72596. _this.lensFlareFinalPostProcess = null;
  72597. _this.hdrFinalPostProcess = null;
  72598. _this.lensFlarePostProcess = null;
  72599. _this.lensFlareComposePostProcess = null;
  72600. _this.motionBlurPostProcess = null;
  72601. _this.depthOfFieldPostProcess = null;
  72602. // Values
  72603. _this.brightThreshold = 1.0;
  72604. _this.blurWidth = 512.0;
  72605. _this.horizontalBlur = false;
  72606. _this.exposure = 1.0;
  72607. _this.lensTexture = null;
  72608. _this.volumetricLightCoefficient = 0.2;
  72609. _this.volumetricLightPower = 4.0;
  72610. _this.volumetricLightBlurScale = 64.0;
  72611. _this.sourceLight = null;
  72612. _this.hdrMinimumLuminance = 1.0;
  72613. _this.hdrDecreaseRate = 0.5;
  72614. _this.hdrIncreaseRate = 0.5;
  72615. _this.lensColorTexture = null;
  72616. _this.lensFlareStrength = 20.0;
  72617. _this.lensFlareGhostDispersal = 1.4;
  72618. _this.lensFlareHaloWidth = 0.7;
  72619. _this.lensFlareDistortionStrength = 16.0;
  72620. _this.lensStarTexture = null;
  72621. _this.lensFlareDirtTexture = null;
  72622. _this.depthOfFieldDistance = 10.0;
  72623. _this.depthOfFieldBlurWidth = 64.0;
  72624. _this.motionStrength = 1.0;
  72625. // IAnimatable
  72626. _this.animations = [];
  72627. _this._currentDepthOfFieldSource = null;
  72628. _this._hdrCurrentLuminance = 1.0;
  72629. // Getters and setters
  72630. _this._bloomEnabled = true;
  72631. _this._depthOfFieldEnabled = false;
  72632. _this._vlsEnabled = false;
  72633. _this._lensFlareEnabled = false;
  72634. _this._hdrEnabled = false;
  72635. _this._motionBlurEnabled = false;
  72636. _this._motionBlurSamples = 64.0;
  72637. _this._volumetricLightStepsCount = 50.0;
  72638. _this._cameras = cameras || [];
  72639. // Initialize
  72640. _this._scene = scene;
  72641. _this._basePostProcess = originalPostProcess;
  72642. _this._ratio = ratio;
  72643. // Misc
  72644. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72645. // Finish
  72646. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72647. _this._buildPipeline();
  72648. return _this;
  72649. }
  72650. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  72651. get: function () {
  72652. return this._bloomEnabled;
  72653. },
  72654. set: function (enabled) {
  72655. if (this._bloomEnabled === enabled) {
  72656. return;
  72657. }
  72658. this._bloomEnabled = enabled;
  72659. this._buildPipeline();
  72660. },
  72661. enumerable: true,
  72662. configurable: true
  72663. });
  72664. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  72665. get: function () {
  72666. return this._depthOfFieldEnabled;
  72667. },
  72668. set: function (enabled) {
  72669. if (this._depthOfFieldEnabled === enabled) {
  72670. return;
  72671. }
  72672. this._depthOfFieldEnabled = enabled;
  72673. this._buildPipeline();
  72674. },
  72675. enumerable: true,
  72676. configurable: true
  72677. });
  72678. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  72679. get: function () {
  72680. return this._lensFlareEnabled;
  72681. },
  72682. set: function (enabled) {
  72683. if (this._lensFlareEnabled === enabled) {
  72684. return;
  72685. }
  72686. this._lensFlareEnabled = enabled;
  72687. this._buildPipeline();
  72688. },
  72689. enumerable: true,
  72690. configurable: true
  72691. });
  72692. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  72693. get: function () {
  72694. return this._hdrEnabled;
  72695. },
  72696. set: function (enabled) {
  72697. if (this._hdrEnabled === enabled) {
  72698. return;
  72699. }
  72700. this._hdrEnabled = enabled;
  72701. this._buildPipeline();
  72702. },
  72703. enumerable: true,
  72704. configurable: true
  72705. });
  72706. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  72707. get: function () {
  72708. return this._vlsEnabled;
  72709. },
  72710. set: function (enabled) {
  72711. if (this._vlsEnabled === enabled) {
  72712. return;
  72713. }
  72714. if (enabled) {
  72715. var geometry = this._scene.enableGeometryBufferRenderer();
  72716. if (!geometry) {
  72717. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  72718. return;
  72719. }
  72720. }
  72721. this._vlsEnabled = enabled;
  72722. this._buildPipeline();
  72723. },
  72724. enumerable: true,
  72725. configurable: true
  72726. });
  72727. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  72728. get: function () {
  72729. return this._motionBlurEnabled;
  72730. },
  72731. set: function (enabled) {
  72732. if (this._motionBlurEnabled === enabled) {
  72733. return;
  72734. }
  72735. this._motionBlurEnabled = enabled;
  72736. this._buildPipeline();
  72737. },
  72738. enumerable: true,
  72739. configurable: true
  72740. });
  72741. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  72742. get: function () {
  72743. return this._volumetricLightStepsCount;
  72744. },
  72745. set: function (count) {
  72746. if (this.volumetricLightPostProcess) {
  72747. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  72748. }
  72749. this._volumetricLightStepsCount = count;
  72750. },
  72751. enumerable: true,
  72752. configurable: true
  72753. });
  72754. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  72755. get: function () {
  72756. return this._motionBlurSamples;
  72757. },
  72758. set: function (samples) {
  72759. if (this.motionBlurPostProcess) {
  72760. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  72761. }
  72762. this._motionBlurSamples = samples;
  72763. },
  72764. enumerable: true,
  72765. configurable: true
  72766. });
  72767. StandardRenderingPipeline.prototype._buildPipeline = function () {
  72768. var _this = this;
  72769. var ratio = this._ratio;
  72770. var scene = this._scene;
  72771. this._disposePostProcesses();
  72772. this._reset();
  72773. // Create pass post-process
  72774. if (!this._basePostProcess) {
  72775. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  72776. this.originalPostProcess.onApply = function (effect) {
  72777. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  72778. };
  72779. }
  72780. else {
  72781. this.originalPostProcess = this._basePostProcess;
  72782. }
  72783. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  72784. this._currentDepthOfFieldSource = this.originalPostProcess;
  72785. if (this._vlsEnabled) {
  72786. // Create volumetric light
  72787. this._createVolumetricLightPostProcess(scene, ratio);
  72788. // Create volumetric light final post-process
  72789. 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);
  72790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  72791. }
  72792. if (this._bloomEnabled) {
  72793. // Create down sample X4 post-process
  72794. this._createDownSampleX4PostProcess(scene, ratio / 2);
  72795. // Create bright pass post-process
  72796. this._createBrightPassPostProcess(scene, ratio / 2);
  72797. // Create gaussian blur post-processes (down sampling blurs)
  72798. this._createBlurPostProcesses(scene, ratio / 4, 1);
  72799. // Create texture adder post-process
  72800. this._createTextureAdderPostProcess(scene, ratio);
  72801. // Create depth-of-field source post-process
  72802. 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);
  72803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  72804. }
  72805. if (this._lensFlareEnabled) {
  72806. // Create lens flare post-process
  72807. this._createLensFlarePostProcess(scene, ratio);
  72808. // Create depth-of-field source post-process post lens-flare and disable it now
  72809. 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);
  72810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  72811. }
  72812. if (this._hdrEnabled) {
  72813. // Create luminance
  72814. this._createLuminancePostProcesses(scene, this._floatTextureType);
  72815. // Create HDR
  72816. this._createHdrPostProcess(scene, ratio);
  72817. // Create depth-of-field source post-process post hdr and disable it now
  72818. 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);
  72819. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  72820. }
  72821. if (this._depthOfFieldEnabled) {
  72822. // Create gaussian blur used by depth-of-field
  72823. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  72824. // Create depth-of-field post-process
  72825. this._createDepthOfFieldPostProcess(scene, ratio);
  72826. }
  72827. if (this._motionBlurEnabled) {
  72828. // Create motion blur post-process
  72829. this._createMotionBlurPostProcess(scene, ratio);
  72830. }
  72831. if (this._cameras !== null) {
  72832. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  72833. }
  72834. };
  72835. // Down Sample X4 Post-Processs
  72836. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  72837. var _this = this;
  72838. var downSampleX4Offsets = new Array(32);
  72839. 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);
  72840. this.downSampleX4PostProcess.onApply = function (effect) {
  72841. var id = 0;
  72842. var width = _this.downSampleX4PostProcess.width;
  72843. var height = _this.downSampleX4PostProcess.height;
  72844. for (var i = -2; i < 2; i++) {
  72845. for (var j = -2; j < 2; j++) {
  72846. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  72847. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  72848. id += 2;
  72849. }
  72850. }
  72851. effect.setArray2("dsOffsets", downSampleX4Offsets);
  72852. };
  72853. // Add to pipeline
  72854. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  72855. };
  72856. // Brightpass Post-Process
  72857. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  72858. var _this = this;
  72859. var brightOffsets = new Array(8);
  72860. 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);
  72861. this.brightPassPostProcess.onApply = function (effect) {
  72862. var sU = (1.0 / _this.brightPassPostProcess.width);
  72863. var sV = (1.0 / _this.brightPassPostProcess.height);
  72864. brightOffsets[0] = -0.5 * sU;
  72865. brightOffsets[1] = 0.5 * sV;
  72866. brightOffsets[2] = 0.5 * sU;
  72867. brightOffsets[3] = 0.5 * sV;
  72868. brightOffsets[4] = -0.5 * sU;
  72869. brightOffsets[5] = -0.5 * sV;
  72870. brightOffsets[6] = 0.5 * sU;
  72871. brightOffsets[7] = -0.5 * sV;
  72872. effect.setArray2("dsOffsets", brightOffsets);
  72873. effect.setFloat("brightThreshold", _this.brightThreshold);
  72874. };
  72875. // Add to pipeline
  72876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  72877. };
  72878. // Create blur H&V post-processes
  72879. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  72880. var _this = this;
  72881. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  72882. var engine = scene.getEngine();
  72883. 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);
  72884. 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);
  72885. blurX.onActivateObservable.add(function () {
  72886. var dw = blurX.width / engine.getRenderWidth();
  72887. blurX.kernel = _this[blurWidthKey] * dw;
  72888. });
  72889. blurY.onActivateObservable.add(function () {
  72890. var dw = blurY.height / engine.getRenderHeight();
  72891. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  72892. });
  72893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  72894. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  72895. this.blurHPostProcesses.push(blurX);
  72896. this.blurVPostProcesses.push(blurY);
  72897. };
  72898. // Create texture adder post-process
  72899. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  72900. var _this = this;
  72901. 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);
  72902. this.textureAdderPostProcess.onApply = function (effect) {
  72903. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  72904. effect.setTexture("lensSampler", _this.lensTexture);
  72905. effect.setFloat("exposure", _this.exposure);
  72906. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  72907. };
  72908. // Add to pipeline
  72909. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  72910. };
  72911. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  72912. var _this = this;
  72913. var geometryRenderer = scene.enableGeometryBufferRenderer();
  72914. geometryRenderer.enablePosition = true;
  72915. var geometry = geometryRenderer.getGBuffer();
  72916. // Base post-process
  72917. 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));
  72918. var depthValues = BABYLON.Vector2.Zero();
  72919. this.volumetricLightPostProcess.onApply = function (effect) {
  72920. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  72921. var generator = _this.sourceLight.getShadowGenerator();
  72922. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  72923. effect.setTexture("positionSampler", geometry.textures[2]);
  72924. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  72925. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  72926. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  72927. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  72928. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  72929. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  72930. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  72931. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  72932. effect.setVector2("depthValues", depthValues);
  72933. }
  72934. };
  72935. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  72936. // Smooth
  72937. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  72938. // Merge
  72939. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  72940. this.volumetricLightMergePostProces.onApply = function (effect) {
  72941. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  72942. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  72943. };
  72944. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  72945. };
  72946. // Create luminance
  72947. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  72948. var _this = this;
  72949. // Create luminance
  72950. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  72951. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  72952. var offsets = [];
  72953. this.luminancePostProcess.onApply = function (effect) {
  72954. var sU = (1.0 / _this.luminancePostProcess.width);
  72955. var sV = (1.0 / _this.luminancePostProcess.height);
  72956. offsets[0] = -0.5 * sU;
  72957. offsets[1] = 0.5 * sV;
  72958. offsets[2] = 0.5 * sU;
  72959. offsets[3] = 0.5 * sV;
  72960. offsets[4] = -0.5 * sU;
  72961. offsets[5] = -0.5 * sV;
  72962. offsets[6] = 0.5 * sU;
  72963. offsets[7] = -0.5 * sV;
  72964. effect.setArray2("lumOffsets", offsets);
  72965. };
  72966. // Add to pipeline
  72967. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  72968. // Create down sample luminance
  72969. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  72970. var size = Math.pow(3, i);
  72971. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  72972. if (i === 0) {
  72973. defines += "#define FINAL_DOWN_SAMPLER";
  72974. }
  72975. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  72976. this.luminanceDownSamplePostProcesses.push(postProcess);
  72977. }
  72978. // Create callbacks and add effects
  72979. var lastLuminance = this.luminancePostProcess;
  72980. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  72981. var downSampleOffsets = new Array(18);
  72982. pp.onApply = function (effect) {
  72983. if (!lastLuminance) {
  72984. return;
  72985. }
  72986. var id = 0;
  72987. for (var x = -1; x < 2; x++) {
  72988. for (var y = -1; y < 2; y++) {
  72989. downSampleOffsets[id] = x / lastLuminance.width;
  72990. downSampleOffsets[id + 1] = y / lastLuminance.height;
  72991. id += 2;
  72992. }
  72993. }
  72994. effect.setArray2("dsOffsets", downSampleOffsets);
  72995. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  72996. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72997. lastLuminance = _this.luminancePostProcess;
  72998. }
  72999. else {
  73000. lastLuminance = pp;
  73001. }
  73002. };
  73003. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73004. pp.onAfterRender = function (effect) {
  73005. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73006. 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);
  73007. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73008. };
  73009. }
  73010. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73011. });
  73012. };
  73013. // Create HDR post-process
  73014. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73015. var _this = this;
  73016. 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);
  73017. var outputLiminance = 1;
  73018. var time = 0;
  73019. var lastTime = 0;
  73020. this.hdrPostProcess.onApply = function (effect) {
  73021. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73022. time += scene.getEngine().getDeltaTime();
  73023. if (outputLiminance < 0) {
  73024. outputLiminance = _this._hdrCurrentLuminance;
  73025. }
  73026. else {
  73027. var dt = (lastTime - time) / 1000.0;
  73028. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73029. outputLiminance += _this.hdrDecreaseRate * dt;
  73030. }
  73031. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73032. outputLiminance -= _this.hdrIncreaseRate * dt;
  73033. }
  73034. else {
  73035. outputLiminance = _this._hdrCurrentLuminance;
  73036. }
  73037. }
  73038. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73039. effect.setFloat("averageLuminance", outputLiminance);
  73040. lastTime = time;
  73041. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73042. };
  73043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73044. };
  73045. // Create lens flare post-process
  73046. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73047. var _this = this;
  73048. 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);
  73049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73050. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73051. 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);
  73052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73053. var resolution = new BABYLON.Vector2(0, 0);
  73054. // Lens flare
  73055. this.lensFlarePostProcess.onApply = function (effect) {
  73056. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73057. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73058. effect.setFloat("strength", _this.lensFlareStrength);
  73059. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73060. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73061. // Shift
  73062. resolution.x = _this.lensFlarePostProcess.width;
  73063. resolution.y = _this.lensFlarePostProcess.height;
  73064. effect.setVector2("resolution", resolution);
  73065. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73066. };
  73067. // Compose
  73068. 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);
  73069. 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);
  73070. this.lensFlareComposePostProcess.onApply = function (effect) {
  73071. if (!_this._scene.activeCamera) {
  73072. return;
  73073. }
  73074. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73075. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73076. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73077. // Lens start rotation matrix
  73078. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73079. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73080. 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));
  73081. camRot *= 4.0;
  73082. 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);
  73083. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73084. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73085. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73086. };
  73087. };
  73088. // Create depth-of-field post-process
  73089. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73090. var _this = this;
  73091. 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);
  73092. this.depthOfFieldPostProcess.onApply = function (effect) {
  73093. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73094. effect.setTexture("depthSampler", _this._getDepthTexture());
  73095. effect.setFloat("distance", _this.depthOfFieldDistance);
  73096. };
  73097. // Add to pipeline
  73098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73099. };
  73100. // Create motion blur post-process
  73101. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73102. var _this = this;
  73103. 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);
  73104. var motionScale = 0;
  73105. var prevViewProjection = BABYLON.Matrix.Identity();
  73106. var invViewProjection = BABYLON.Matrix.Identity();
  73107. var viewProjection = BABYLON.Matrix.Identity();
  73108. var screenSize = BABYLON.Vector2.Zero();
  73109. this.motionBlurPostProcess.onApply = function (effect) {
  73110. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73111. viewProjection.invertToRef(invViewProjection);
  73112. effect.setMatrix("inverseViewProjection", invViewProjection);
  73113. effect.setMatrix("prevViewProjection", prevViewProjection);
  73114. prevViewProjection = viewProjection;
  73115. screenSize.x = _this.motionBlurPostProcess.width;
  73116. screenSize.y = _this.motionBlurPostProcess.height;
  73117. effect.setVector2("screenSize", screenSize);
  73118. motionScale = scene.getEngine().getFps() / 60.0;
  73119. effect.setFloat("motionScale", motionScale);
  73120. effect.setFloat("motionStrength", _this.motionStrength);
  73121. effect.setTexture("depthSampler", _this._getDepthTexture());
  73122. };
  73123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73124. };
  73125. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73126. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73127. var renderer = this._scene.enableGeometryBufferRenderer();
  73128. return renderer.getGBuffer().textures[0];
  73129. }
  73130. return this._scene.enableDepthRenderer().getDepthMap();
  73131. };
  73132. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73133. for (var i = 0; i < this._cameras.length; i++) {
  73134. var camera = this._cameras[i];
  73135. if (this.originalPostProcess) {
  73136. this.originalPostProcess.dispose(camera);
  73137. }
  73138. if (this.downSampleX4PostProcess) {
  73139. this.downSampleX4PostProcess.dispose(camera);
  73140. }
  73141. if (this.brightPassPostProcess) {
  73142. this.brightPassPostProcess.dispose(camera);
  73143. }
  73144. if (this.textureAdderPostProcess) {
  73145. this.textureAdderPostProcess.dispose(camera);
  73146. }
  73147. if (this.textureAdderFinalPostProcess) {
  73148. this.textureAdderFinalPostProcess.dispose(camera);
  73149. }
  73150. if (this.volumetricLightPostProcess) {
  73151. this.volumetricLightPostProcess.dispose(camera);
  73152. }
  73153. if (this.volumetricLightSmoothXPostProcess) {
  73154. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73155. }
  73156. if (this.volumetricLightSmoothYPostProcess) {
  73157. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73158. }
  73159. if (this.volumetricLightMergePostProces) {
  73160. this.volumetricLightMergePostProces.dispose(camera);
  73161. }
  73162. if (this.volumetricLightFinalPostProcess) {
  73163. this.volumetricLightFinalPostProcess.dispose(camera);
  73164. }
  73165. if (this.lensFlarePostProcess) {
  73166. this.lensFlarePostProcess.dispose(camera);
  73167. }
  73168. if (this.lensFlareComposePostProcess) {
  73169. this.lensFlareComposePostProcess.dispose(camera);
  73170. }
  73171. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73172. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73173. }
  73174. if (this.luminancePostProcess) {
  73175. this.luminancePostProcess.dispose(camera);
  73176. }
  73177. if (this.hdrPostProcess) {
  73178. this.hdrPostProcess.dispose(camera);
  73179. }
  73180. if (this.hdrFinalPostProcess) {
  73181. this.hdrFinalPostProcess.dispose(camera);
  73182. }
  73183. if (this.depthOfFieldPostProcess) {
  73184. this.depthOfFieldPostProcess.dispose(camera);
  73185. }
  73186. if (this.motionBlurPostProcess) {
  73187. this.motionBlurPostProcess.dispose(camera);
  73188. }
  73189. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73190. this.blurHPostProcesses[j].dispose(camera);
  73191. }
  73192. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73193. this.blurVPostProcesses[j].dispose(camera);
  73194. }
  73195. }
  73196. this.originalPostProcess = null;
  73197. this.downSampleX4PostProcess = null;
  73198. this.brightPassPostProcess = null;
  73199. this.textureAdderPostProcess = null;
  73200. this.textureAdderFinalPostProcess = null;
  73201. this.volumetricLightPostProcess = null;
  73202. this.volumetricLightSmoothXPostProcess = null;
  73203. this.volumetricLightSmoothYPostProcess = null;
  73204. this.volumetricLightMergePostProces = null;
  73205. this.volumetricLightFinalPostProcess = null;
  73206. this.lensFlarePostProcess = null;
  73207. this.lensFlareComposePostProcess = null;
  73208. this.luminancePostProcess = null;
  73209. this.hdrPostProcess = null;
  73210. this.hdrFinalPostProcess = null;
  73211. this.depthOfFieldPostProcess = null;
  73212. this.motionBlurPostProcess = null;
  73213. this.luminanceDownSamplePostProcesses = [];
  73214. this.blurHPostProcesses = [];
  73215. this.blurVPostProcesses = [];
  73216. };
  73217. // Dispose
  73218. StandardRenderingPipeline.prototype.dispose = function () {
  73219. this._disposePostProcesses();
  73220. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73221. _super.prototype.dispose.call(this);
  73222. };
  73223. // Serialize rendering pipeline
  73224. StandardRenderingPipeline.prototype.serialize = function () {
  73225. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73226. serializationObject.customType = "StandardRenderingPipeline";
  73227. return serializationObject;
  73228. };
  73229. /**
  73230. * Static members
  73231. */
  73232. // Parse serialized pipeline
  73233. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73234. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73235. };
  73236. // Luminance steps
  73237. StandardRenderingPipeline.LuminanceSteps = 6;
  73238. __decorate([
  73239. BABYLON.serialize()
  73240. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73241. __decorate([
  73242. BABYLON.serialize()
  73243. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73244. __decorate([
  73245. BABYLON.serialize()
  73246. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73247. __decorate([
  73248. BABYLON.serialize()
  73249. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73250. __decorate([
  73251. BABYLON.serializeAsTexture("lensTexture")
  73252. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73253. __decorate([
  73254. BABYLON.serialize()
  73255. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73256. __decorate([
  73257. BABYLON.serialize()
  73258. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73259. __decorate([
  73260. BABYLON.serialize()
  73261. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73262. __decorate([
  73263. BABYLON.serialize()
  73264. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73265. __decorate([
  73266. BABYLON.serialize()
  73267. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73268. __decorate([
  73269. BABYLON.serialize()
  73270. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73271. __decorate([
  73272. BABYLON.serializeAsTexture("lensColorTexture")
  73273. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73274. __decorate([
  73275. BABYLON.serialize()
  73276. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73277. __decorate([
  73278. BABYLON.serialize()
  73279. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73280. __decorate([
  73281. BABYLON.serialize()
  73282. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73283. __decorate([
  73284. BABYLON.serialize()
  73285. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73286. __decorate([
  73287. BABYLON.serializeAsTexture("lensStarTexture")
  73288. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73289. __decorate([
  73290. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73291. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73292. __decorate([
  73293. BABYLON.serialize()
  73294. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73295. __decorate([
  73296. BABYLON.serialize()
  73297. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73298. __decorate([
  73299. BABYLON.serialize()
  73300. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73301. __decorate([
  73302. BABYLON.serialize()
  73303. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73304. __decorate([
  73305. BABYLON.serialize()
  73306. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73307. __decorate([
  73308. BABYLON.serialize()
  73309. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73310. __decorate([
  73311. BABYLON.serialize()
  73312. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73313. __decorate([
  73314. BABYLON.serialize()
  73315. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73316. __decorate([
  73317. BABYLON.serialize()
  73318. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73319. __decorate([
  73320. BABYLON.serialize()
  73321. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73322. __decorate([
  73323. BABYLON.serialize()
  73324. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73325. __decorate([
  73326. BABYLON.serialize()
  73327. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73328. return StandardRenderingPipeline;
  73329. }(BABYLON.PostProcessRenderPipeline));
  73330. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73331. })(BABYLON || (BABYLON = {}));
  73332. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73333. "use strict";
  73334. var BABYLON;
  73335. (function (BABYLON) {
  73336. var FxaaPostProcess = /** @class */ (function (_super) {
  73337. __extends(FxaaPostProcess, _super);
  73338. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73339. if (camera === void 0) { camera = null; }
  73340. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73341. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73342. _this.onApplyObservable.add(function (effect) {
  73343. var texelSize = _this.texelSize;
  73344. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73345. });
  73346. return _this;
  73347. }
  73348. return FxaaPostProcess;
  73349. }(BABYLON.PostProcess));
  73350. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73351. })(BABYLON || (BABYLON = {}));
  73352. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73353. "use strict";
  73354. var BABYLON;
  73355. (function (BABYLON) {
  73356. /**
  73357. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73358. */
  73359. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73360. __extends(ChromaticAberrationPostProcess, _super);
  73361. /**
  73362. * Creates a new instance ChromaticAberrationPostProcess
  73363. * @param name The name of the effect.
  73364. * @param screenWidth The width of the screen to apply the effect on.
  73365. * @param screenHeight The height of the screen to apply the effect on.
  73366. * @param options The required width/height ratio to downsize to before computing the render pass.
  73367. * @param camera The camera to apply the render pass to.
  73368. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73369. * @param engine The engine which the post process will be applied. (default: current engine)
  73370. * @param reusable If the post process can be reused on the same frame. (default: false)
  73371. * @param textureType Type of textures used when performing the post process. (default: 0)
  73372. * @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)
  73373. */
  73374. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73375. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73376. if (blockCompilation === void 0) { blockCompilation = false; }
  73377. 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;
  73378. /**
  73379. * The amount of seperation of rgb channels (default: 30)
  73380. */
  73381. _this.aberrationAmount = 30;
  73382. /**
  73383. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73384. */
  73385. _this.radialIntensity = 0;
  73386. /**
  73387. * 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))
  73388. */
  73389. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73390. /**
  73391. * 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))
  73392. */
  73393. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73394. _this.onApplyObservable.add(function (effect) {
  73395. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73396. effect.setFloat('screen_width', screenWidth);
  73397. effect.setFloat('screen_height', screenHeight);
  73398. effect.setFloat('radialIntensity', _this.radialIntensity);
  73399. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73400. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73401. });
  73402. return _this;
  73403. }
  73404. return ChromaticAberrationPostProcess;
  73405. }(BABYLON.PostProcess));
  73406. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73407. })(BABYLON || (BABYLON = {}));
  73408. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73409. "use strict";
  73410. var BABYLON;
  73411. (function (BABYLON) {
  73412. /**
  73413. * The GrainPostProcess adds noise to the image at mid luminance levels
  73414. */
  73415. var GrainPostProcess = /** @class */ (function (_super) {
  73416. __extends(GrainPostProcess, _super);
  73417. /**
  73418. * Creates a new instance of @see GrainPostProcess
  73419. * @param name The name of the effect.
  73420. * @param options The required width/height ratio to downsize to before computing the render pass.
  73421. * @param camera The camera to apply the render pass to.
  73422. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73423. * @param engine The engine which the post process will be applied. (default: current engine)
  73424. * @param reusable If the post process can be reused on the same frame. (default: false)
  73425. * @param textureType Type of textures used when performing the post process. (default: 0)
  73426. * @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)
  73427. */
  73428. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73429. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73430. if (blockCompilation === void 0) { blockCompilation = false; }
  73431. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73432. /**
  73433. * The intensity of the grain added (default: 30)
  73434. */
  73435. _this.intensity = 30;
  73436. /**
  73437. * If the grain should be randomized on every frame
  73438. */
  73439. _this.animated = false;
  73440. _this.onApplyObservable.add(function (effect) {
  73441. effect.setFloat('intensity', _this.intensity);
  73442. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73443. });
  73444. return _this;
  73445. }
  73446. return GrainPostProcess;
  73447. }(BABYLON.PostProcess));
  73448. BABYLON.GrainPostProcess = GrainPostProcess;
  73449. })(BABYLON || (BABYLON = {}));
  73450. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73451. "use strict";
  73452. var BABYLON;
  73453. (function (BABYLON) {
  73454. /**
  73455. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73456. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73457. */
  73458. var SharpenPostProcess = /** @class */ (function (_super) {
  73459. __extends(SharpenPostProcess, _super);
  73460. /**
  73461. * Creates a new instance ConvolutionPostProcess
  73462. * @param name The name of the effect.
  73463. * @param options The required width/height ratio to downsize to before computing the render pass.
  73464. * @param camera The camera to apply the render pass to.
  73465. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73466. * @param engine The engine which the post process will be applied. (default: current engine)
  73467. * @param reusable If the post process can be reused on the same frame. (default: false)
  73468. * @param textureType Type of textures used when performing the post process. (default: 0)
  73469. * @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)
  73470. */
  73471. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73472. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73473. if (blockCompilation === void 0) { blockCompilation = false; }
  73474. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73475. /**
  73476. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73477. */
  73478. _this.colorAmount = 1.0;
  73479. /**
  73480. * How much sharpness should be applied (default: 0.3)
  73481. */
  73482. _this.edgeAmount = 0.3;
  73483. _this.onApply = function (effect) {
  73484. effect.setFloat2("screenSize", _this.width, _this.height);
  73485. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73486. };
  73487. return _this;
  73488. }
  73489. return SharpenPostProcess;
  73490. }(BABYLON.PostProcess));
  73491. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73492. })(BABYLON || (BABYLON = {}));
  73493. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73494. "use strict";
  73495. var BABYLON;
  73496. (function (BABYLON) {
  73497. /**
  73498. * The Blur Post Process which blurs an image based on a kernel and direction.
  73499. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  73500. */
  73501. var BlurPostProcess = /** @class */ (function (_super) {
  73502. __extends(BlurPostProcess, _super);
  73503. /**
  73504. * Creates a new instance BlurPostProcess
  73505. * @param name The name of the effect.
  73506. * @param direction The direction in which to blur the image.
  73507. * @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.
  73508. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73509. * @param camera The camera to apply the render pass to.
  73510. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73511. * @param engine The engine which the post process will be applied. (default: current engine)
  73512. * @param reusable If the post process can be reused on the same frame. (default: false)
  73513. * @param textureType Type of textures used when performing the post process. (default: 0)
  73514. * @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)
  73515. */
  73516. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  73517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73518. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73519. if (defines === void 0) { defines = ""; }
  73520. if (blockCompilation === void 0) { blockCompilation = false; }
  73521. 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;
  73522. _this.direction = direction;
  73523. _this.blockCompilation = blockCompilation;
  73524. _this._packedFloat = false;
  73525. _this._staticDefines = "";
  73526. _this._staticDefines = defines;
  73527. _this.onApplyObservable.add(function (effect) {
  73528. if (_this._outputTexture) {
  73529. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  73530. }
  73531. else {
  73532. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  73533. }
  73534. });
  73535. _this.kernel = kernel;
  73536. return _this;
  73537. }
  73538. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  73539. /**
  73540. * Gets the length in pixels of the blur sample region
  73541. */
  73542. get: function () {
  73543. return this._idealKernel;
  73544. },
  73545. /**
  73546. * Sets the length in pixels of the blur sample region
  73547. */
  73548. set: function (v) {
  73549. if (this._idealKernel === v) {
  73550. return;
  73551. }
  73552. v = Math.max(v, 1);
  73553. this._idealKernel = v;
  73554. this._kernel = this._nearestBestKernel(v);
  73555. if (!this.blockCompilation) {
  73556. this._updateParameters();
  73557. }
  73558. },
  73559. enumerable: true,
  73560. configurable: true
  73561. });
  73562. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  73563. /**
  73564. * Gets wether or not the blur is unpacking/repacking floats
  73565. */
  73566. get: function () {
  73567. return this._packedFloat;
  73568. },
  73569. /**
  73570. * Sets wether or not the blur needs to unpack/repack floats
  73571. */
  73572. set: function (v) {
  73573. if (this._packedFloat === v) {
  73574. return;
  73575. }
  73576. this._packedFloat = v;
  73577. if (!this.blockCompilation) {
  73578. this._updateParameters();
  73579. }
  73580. },
  73581. enumerable: true,
  73582. configurable: true
  73583. });
  73584. /**
  73585. * Updates the effect with the current post process compile time values and recompiles the shader.
  73586. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73587. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73588. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73589. * @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
  73590. * @param onCompiled Called when the shader has been compiled.
  73591. * @param onError Called if there is an error when compiling a shader.
  73592. */
  73593. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73594. if (defines === void 0) { defines = null; }
  73595. if (uniforms === void 0) { uniforms = null; }
  73596. if (samplers === void 0) { samplers = null; }
  73597. this._updateParameters(onCompiled, onError);
  73598. };
  73599. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73600. // Generate sampling offsets and weights
  73601. var N = this._kernel;
  73602. var centerIndex = (N - 1) / 2;
  73603. // Generate Gaussian sampling weights over kernel
  73604. var offsets = [];
  73605. var weights = [];
  73606. var totalWeight = 0;
  73607. for (var i = 0; i < N; i++) {
  73608. var u = i / (N - 1);
  73609. var w = this._gaussianWeight(u * 2.0 - 1);
  73610. offsets[i] = (i - centerIndex);
  73611. weights[i] = w;
  73612. totalWeight += w;
  73613. }
  73614. // Normalize weights
  73615. for (var i = 0; i < weights.length; i++) {
  73616. weights[i] /= totalWeight;
  73617. }
  73618. // Optimize: combine samples to take advantage of hardware linear sampling
  73619. // Walk from left to center, combining pairs (symmetrically)
  73620. var linearSamplingWeights = [];
  73621. var linearSamplingOffsets = [];
  73622. var linearSamplingMap = [];
  73623. for (var i = 0; i <= centerIndex; i += 2) {
  73624. var j = Math.min(i + 1, Math.floor(centerIndex));
  73625. var singleCenterSample = i === j;
  73626. if (singleCenterSample) {
  73627. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73628. }
  73629. else {
  73630. var sharedCell = j === centerIndex;
  73631. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73632. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  73633. if (offsetLinear === 0) {
  73634. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73635. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  73636. }
  73637. else {
  73638. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  73639. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  73640. }
  73641. }
  73642. }
  73643. for (var i = 0; i < linearSamplingMap.length; i++) {
  73644. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  73645. linearSamplingWeights[i] = linearSamplingMap[i].w;
  73646. }
  73647. // Replace with optimized
  73648. offsets = linearSamplingOffsets;
  73649. weights = linearSamplingWeights;
  73650. // Generate shaders
  73651. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  73652. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  73653. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  73654. var defines = "";
  73655. defines += this._staticDefines;
  73656. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  73657. if (this._staticDefines.indexOf("DOF") != -1) {
  73658. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  73659. varyingCount--;
  73660. }
  73661. for (var i = 0; i < varyingCount; i++) {
  73662. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  73663. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  73664. }
  73665. var depCount = 0;
  73666. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  73667. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  73668. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  73669. depCount++;
  73670. }
  73671. if (this.packedFloat) {
  73672. defines += "#define PACKEDFLOAT 1";
  73673. }
  73674. this.blockCompilation = false;
  73675. _super.prototype.updateEffect.call(this, defines, null, null, {
  73676. varyingCount: varyingCount,
  73677. depCount: depCount
  73678. }, onCompiled, onError);
  73679. };
  73680. /**
  73681. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  73682. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  73683. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  73684. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  73685. * The gaps between physical kernels are compensated for in the weighting of the samples
  73686. * @param idealKernel Ideal blur kernel.
  73687. * @return Nearest best kernel.
  73688. */
  73689. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  73690. var v = Math.round(idealKernel);
  73691. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  73692. var k = _a[_i];
  73693. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  73694. return Math.max(k, 3);
  73695. }
  73696. }
  73697. return Math.max(v, 3);
  73698. };
  73699. /**
  73700. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  73701. * @param x The point on the Gaussian distribution to sample.
  73702. * @return the value of the Gaussian function at x.
  73703. */
  73704. BlurPostProcess.prototype._gaussianWeight = function (x) {
  73705. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  73706. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  73707. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  73708. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  73709. // truncated at around 1.3% of peak strength.
  73710. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  73711. var sigma = (1 / 3);
  73712. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  73713. var exponent = -((x * x) / (2.0 * sigma * sigma));
  73714. var weight = (1.0 / denominator) * Math.exp(exponent);
  73715. return weight;
  73716. };
  73717. /**
  73718. * Generates a string that can be used as a floating point number in GLSL.
  73719. * @param x Value to print.
  73720. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  73721. * @return GLSL float string.
  73722. */
  73723. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  73724. if (decimalFigures === void 0) { decimalFigures = 8; }
  73725. return x.toFixed(decimalFigures).replace(/0+$/, '');
  73726. };
  73727. return BlurPostProcess;
  73728. }(BABYLON.PostProcess));
  73729. BABYLON.BlurPostProcess = BlurPostProcess;
  73730. })(BABYLON || (BABYLON = {}));
  73731. //# sourceMappingURL=babylon.blurPostProcess.js.map
  73732. "use strict";
  73733. var BABYLON;
  73734. (function (BABYLON) {
  73735. /**
  73736. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  73737. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  73738. * based on samples that have a large difference in distance than the center pixel.
  73739. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73740. */
  73741. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  73742. __extends(DepthOfFieldBlurPostProcess, _super);
  73743. /**
  73744. * Creates a new instance CircleOfConfusionPostProcess
  73745. * @param name The name of the effect.
  73746. * @param scene The scene the effect belongs to.
  73747. * @param direction The direction the blur should be applied.
  73748. * @param kernel The size of the kernel used to blur.
  73749. * @param options The required width/height ratio to downsize to before computing the render pass.
  73750. * @param camera The camera to apply the render pass to.
  73751. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  73752. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  73753. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73754. * @param engine The engine which the post process will be applied. (default: current engine)
  73755. * @param reusable If the post process can be reused on the same frame. (default: false)
  73756. * @param textureType Type of textures used when performing the post process. (default: 0)
  73757. * @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)
  73758. */
  73759. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  73760. if (imageToBlur === void 0) { imageToBlur = null; }
  73761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73762. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73763. if (blockCompilation === void 0) { blockCompilation = false; }
  73764. 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;
  73765. _this.direction = direction;
  73766. _this.onApplyObservable.add(function (effect) {
  73767. if (imageToBlur != null) {
  73768. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  73769. }
  73770. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73771. if (scene.activeCamera) {
  73772. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73773. }
  73774. });
  73775. return _this;
  73776. }
  73777. return DepthOfFieldBlurPostProcess;
  73778. }(BABYLON.BlurPostProcess));
  73779. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  73780. })(BABYLON || (BABYLON = {}));
  73781. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  73782. "use strict";
  73783. var BABYLON;
  73784. (function (BABYLON) {
  73785. /**
  73786. * Options to be set when merging outputs from the default pipeline.
  73787. */
  73788. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  73789. function DepthOfFieldMergePostProcessOptions() {
  73790. }
  73791. return DepthOfFieldMergePostProcessOptions;
  73792. }());
  73793. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  73794. /**
  73795. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73796. */
  73797. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  73798. __extends(DepthOfFieldMergePostProcess, _super);
  73799. /**
  73800. * Creates a new instance of DepthOfFieldMergePostProcess
  73801. * @param name The name of the effect.
  73802. * @param originalFromInput Post process which's input will be used for the merge.
  73803. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  73804. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  73805. * @param options The required width/height ratio to downsize to before computing the render pass.
  73806. * @param camera The camera to apply the render pass to.
  73807. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73808. * @param engine The engine which the post process will be applied. (default: current engine)
  73809. * @param reusable If the post process can be reused on the same frame. (default: false)
  73810. * @param textureType Type of textures used when performing the post process. (default: 0)
  73811. * @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)
  73812. */
  73813. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73814. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73815. if (blockCompilation === void 0) { blockCompilation = false; }
  73816. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73817. _this.blurSteps = blurSteps;
  73818. _this.onApplyObservable.add(function (effect) {
  73819. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73820. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73821. blurSteps.forEach(function (step, index) {
  73822. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  73823. });
  73824. });
  73825. if (!blockCompilation) {
  73826. _this.updateEffect();
  73827. }
  73828. return _this;
  73829. }
  73830. /**
  73831. * Updates the effect with the current post process compile time values and recompiles the shader.
  73832. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73833. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73834. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73835. * @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
  73836. * @param onCompiled Called when the shader has been compiled.
  73837. * @param onError Called if there is an error when compiling a shader.
  73838. */
  73839. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73840. if (defines === void 0) { defines = null; }
  73841. if (uniforms === void 0) { uniforms = null; }
  73842. if (samplers === void 0) { samplers = null; }
  73843. if (!defines) {
  73844. defines = "";
  73845. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  73846. }
  73847. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  73848. };
  73849. return DepthOfFieldMergePostProcess;
  73850. }(BABYLON.PostProcess));
  73851. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  73852. })(BABYLON || (BABYLON = {}));
  73853. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  73854. "use strict";
  73855. var BABYLON;
  73856. (function (BABYLON) {
  73857. /**
  73858. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  73859. */
  73860. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  73861. __extends(CircleOfConfusionPostProcess, _super);
  73862. /**
  73863. * Creates a new instance CircleOfConfusionPostProcess
  73864. * @param name The name of the effect.
  73865. * @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.
  73866. * @param options The required width/height ratio to downsize to before computing the render pass.
  73867. * @param camera The camera to apply the render pass to.
  73868. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73869. * @param engine The engine which the post process will be applied. (default: current engine)
  73870. * @param reusable If the post process can be reused on the same frame. (default: false)
  73871. * @param textureType Type of textures used when performing the post process. (default: 0)
  73872. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  73873. */
  73874. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73875. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73876. if (blockCompilation === void 0) { blockCompilation = false; }
  73877. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73878. /**
  73879. * 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.
  73880. */
  73881. _this.lensSize = 50;
  73882. /**
  73883. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73884. */
  73885. _this.fStop = 1.4;
  73886. /**
  73887. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73888. */
  73889. _this.focusDistance = 2000;
  73890. /**
  73891. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  73892. */
  73893. _this.focalLength = 50;
  73894. _this._depthTexture = null;
  73895. _this._depthTexture = depthTexture;
  73896. _this.onApplyObservable.add(function (effect) {
  73897. if (!_this._depthTexture) {
  73898. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  73899. return;
  73900. }
  73901. effect.setTexture("depthSampler", _this._depthTexture);
  73902. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  73903. var aperture = _this.lensSize / _this.fStop;
  73904. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  73905. effect.setFloat('focusDistance', _this.focusDistance);
  73906. effect.setFloat('cocPrecalculation', cocPrecalculation);
  73907. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  73908. });
  73909. return _this;
  73910. }
  73911. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  73912. /**
  73913. * 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.
  73914. */
  73915. set: function (value) {
  73916. this._depthTexture = value;
  73917. },
  73918. enumerable: true,
  73919. configurable: true
  73920. });
  73921. return CircleOfConfusionPostProcess;
  73922. }(BABYLON.PostProcess));
  73923. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  73924. })(BABYLON || (BABYLON = {}));
  73925. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  73926. "use strict";
  73927. var BABYLON;
  73928. (function (BABYLON) {
  73929. /**
  73930. * Specifies the level of max blur that should be applied when using the depth of field effect
  73931. */
  73932. var DepthOfFieldEffectBlurLevel;
  73933. (function (DepthOfFieldEffectBlurLevel) {
  73934. /**
  73935. * Subtle blur
  73936. */
  73937. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  73938. /**
  73939. * Medium blur
  73940. */
  73941. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  73942. /**
  73943. * Large blur
  73944. */
  73945. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  73946. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  73947. ;
  73948. /**
  73949. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  73950. */
  73951. var DepthOfFieldEffect = /** @class */ (function (_super) {
  73952. __extends(DepthOfFieldEffect, _super);
  73953. /**
  73954. * Creates a new instance DepthOfFieldEffect
  73955. * @param scene The scene the effect belongs to.
  73956. * @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.
  73957. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73958. * @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)
  73959. */
  73960. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  73961. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  73962. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73963. if (blockCompilation === void 0) { blockCompilation = false; }
  73964. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  73965. return _this._effects;
  73966. }, true) || this;
  73967. /**
  73968. * Internal post processes in depth of field effect
  73969. */
  73970. _this._effects = [];
  73971. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  73972. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73973. // 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)
  73974. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  73975. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73976. _this._depthOfFieldBlurY = [];
  73977. _this._depthOfFieldBlurX = [];
  73978. var blurCount = 1;
  73979. var kernelSize = 15;
  73980. switch (blurLevel) {
  73981. case DepthOfFieldEffectBlurLevel.High: {
  73982. blurCount = 3;
  73983. kernelSize = 51;
  73984. break;
  73985. }
  73986. case DepthOfFieldEffectBlurLevel.Medium: {
  73987. blurCount = 2;
  73988. kernelSize = 31;
  73989. break;
  73990. }
  73991. default: {
  73992. kernelSize = 15;
  73993. blurCount = 1;
  73994. break;
  73995. }
  73996. }
  73997. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  73998. var ratio = 1.0;
  73999. for (var i = 0; i < blurCount; i++) {
  74000. 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);
  74001. blurY.autoClear = false;
  74002. ratio = 0.75 / Math.pow(2, i);
  74003. 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);
  74004. blurX.autoClear = false;
  74005. _this._depthOfFieldBlurY.push(blurY);
  74006. _this._depthOfFieldBlurX.push(blurX);
  74007. }
  74008. // Set all post processes on the effect.
  74009. _this._effects = [_this._circleOfConfusion];
  74010. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74011. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74012. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74013. }
  74014. // Merge blurred images with original image based on circleOfConfusion
  74015. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74016. _this._dofMerge.autoClear = false;
  74017. _this._effects.push(_this._dofMerge);
  74018. return _this;
  74019. }
  74020. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74021. get: function () {
  74022. return this._circleOfConfusion.focalLength;
  74023. },
  74024. /**
  74025. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74026. */
  74027. set: function (value) {
  74028. this._circleOfConfusion.focalLength = value;
  74029. },
  74030. enumerable: true,
  74031. configurable: true
  74032. });
  74033. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74034. get: function () {
  74035. return this._circleOfConfusion.fStop;
  74036. },
  74037. /**
  74038. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74039. */
  74040. set: function (value) {
  74041. this._circleOfConfusion.fStop = value;
  74042. },
  74043. enumerable: true,
  74044. configurable: true
  74045. });
  74046. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74047. get: function () {
  74048. return this._circleOfConfusion.focusDistance;
  74049. },
  74050. /**
  74051. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74052. */
  74053. set: function (value) {
  74054. this._circleOfConfusion.focusDistance = value;
  74055. },
  74056. enumerable: true,
  74057. configurable: true
  74058. });
  74059. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74060. get: function () {
  74061. return this._circleOfConfusion.lensSize;
  74062. },
  74063. /**
  74064. * 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.
  74065. */
  74066. set: function (value) {
  74067. this._circleOfConfusion.lensSize = value;
  74068. },
  74069. enumerable: true,
  74070. configurable: true
  74071. });
  74072. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74073. /**
  74074. * 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.
  74075. */
  74076. set: function (value) {
  74077. this._circleOfConfusion.depthTexture = value;
  74078. },
  74079. enumerable: true,
  74080. configurable: true
  74081. });
  74082. /**
  74083. * Disposes each of the internal effects for a given camera.
  74084. * @param camera The camera to dispose the effect on.
  74085. */
  74086. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74087. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74088. this._effects[effectIndex].dispose(camera);
  74089. }
  74090. };
  74091. /**
  74092. * Internal
  74093. */
  74094. DepthOfFieldEffect.prototype._updateEffects = function () {
  74095. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74096. this._effects[effectIndex].updateEffect();
  74097. }
  74098. };
  74099. /**
  74100. * Internal
  74101. * @returns if all the contained post processes are ready.
  74102. */
  74103. DepthOfFieldEffect.prototype._isReady = function () {
  74104. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74105. if (!this._effects[effectIndex].isReady()) {
  74106. return false;
  74107. }
  74108. }
  74109. return true;
  74110. };
  74111. return DepthOfFieldEffect;
  74112. }(BABYLON.PostProcessRenderEffect));
  74113. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74114. })(BABYLON || (BABYLON = {}));
  74115. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74116. "use strict";
  74117. var BABYLON;
  74118. (function (BABYLON) {
  74119. /**
  74120. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74121. */
  74122. var BloomMergePostProcess = /** @class */ (function (_super) {
  74123. __extends(BloomMergePostProcess, _super);
  74124. /**
  74125. * Creates a new instance of @see BloomMergePostProcess
  74126. * @param name The name of the effect.
  74127. * @param originalFromInput Post process which's input will be used for the merge.
  74128. * @param blurred Blurred highlights post process which's output will be used.
  74129. * @param weight Weight of the bloom to be added to the original input.
  74130. * @param options The required width/height ratio to downsize to before computing the render pass.
  74131. * @param camera The camera to apply the render pass to.
  74132. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74133. * @param engine The engine which the post process will be applied. (default: current engine)
  74134. * @param reusable If the post process can be reused on the same frame. (default: false)
  74135. * @param textureType Type of textures used when performing the post process. (default: 0)
  74136. * @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)
  74137. */
  74138. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74139. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74140. if (blockCompilation === void 0) { blockCompilation = false; }
  74141. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74142. _this.weight = weight;
  74143. _this.onApplyObservable.add(function (effect) {
  74144. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74145. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74146. effect.setFloat("bloomWeight", _this.weight);
  74147. });
  74148. if (!blockCompilation) {
  74149. _this.updateEffect();
  74150. }
  74151. return _this;
  74152. }
  74153. return BloomMergePostProcess;
  74154. }(BABYLON.PostProcess));
  74155. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74156. })(BABYLON || (BABYLON = {}));
  74157. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74158. "use strict";
  74159. var BABYLON;
  74160. (function (BABYLON) {
  74161. /**
  74162. * 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.
  74163. */
  74164. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74165. __extends(ExtractHighlightsPostProcess, _super);
  74166. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74167. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74168. if (blockCompilation === void 0) { blockCompilation = false; }
  74169. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74170. /**
  74171. * The luminance threshold, pixels below this value will be set to black.
  74172. */
  74173. _this.threshold = 0.9;
  74174. /**
  74175. * Internal
  74176. */
  74177. _this._exposure = 1;
  74178. /**
  74179. * Post process which has the input texture to be used when performing highlight extraction
  74180. */
  74181. _this._inputPostProcess = null;
  74182. _this.onApplyObservable.add(function (effect) {
  74183. if (_this._inputPostProcess) {
  74184. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74185. }
  74186. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74187. effect.setFloat('exposure', _this._exposure);
  74188. });
  74189. return _this;
  74190. }
  74191. return ExtractHighlightsPostProcess;
  74192. }(BABYLON.PostProcess));
  74193. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74194. })(BABYLON || (BABYLON = {}));
  74195. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74196. "use strict";
  74197. var BABYLON;
  74198. (function (BABYLON) {
  74199. /**
  74200. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74201. */
  74202. var BloomEffect = /** @class */ (function (_super) {
  74203. __extends(BloomEffect, _super);
  74204. /**
  74205. * Creates a new instance of @see BloomEffect
  74206. * @param scene The scene the effect belongs to.
  74207. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74208. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74209. * @param bloomWeight The the strength of bloom.
  74210. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74211. * @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)
  74212. */
  74213. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74214. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74215. if (blockCompilation === void 0) { blockCompilation = false; }
  74216. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74217. return _this._effects;
  74218. }, true) || this;
  74219. _this.bloomScale = bloomScale;
  74220. /**
  74221. * Internal
  74222. */
  74223. _this._effects = [];
  74224. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74225. _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);
  74226. _this._blurX.alwaysForcePOT = true;
  74227. _this._blurX.autoClear = false;
  74228. _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);
  74229. _this._blurY.alwaysForcePOT = true;
  74230. _this._blurY.autoClear = false;
  74231. _this.kernel = bloomKernel;
  74232. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74233. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74234. _this._merge.autoClear = false;
  74235. _this._effects.push(_this._merge);
  74236. return _this;
  74237. }
  74238. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74239. /**
  74240. * The luminance threshold to find bright areas of the image to bloom.
  74241. */
  74242. get: function () {
  74243. return this._downscale.threshold;
  74244. },
  74245. set: function (value) {
  74246. this._downscale.threshold = value;
  74247. },
  74248. enumerable: true,
  74249. configurable: true
  74250. });
  74251. Object.defineProperty(BloomEffect.prototype, "weight", {
  74252. /**
  74253. * The strength of the bloom.
  74254. */
  74255. get: function () {
  74256. return this._merge.weight;
  74257. },
  74258. set: function (value) {
  74259. this._merge.weight = value;
  74260. },
  74261. enumerable: true,
  74262. configurable: true
  74263. });
  74264. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74265. /**
  74266. * Specifies the size of the bloom blur kernel, relative to the final output size
  74267. */
  74268. get: function () {
  74269. return this._blurX.kernel / this.bloomScale;
  74270. },
  74271. set: function (value) {
  74272. this._blurX.kernel = value * this.bloomScale;
  74273. this._blurY.kernel = value * this.bloomScale;
  74274. },
  74275. enumerable: true,
  74276. configurable: true
  74277. });
  74278. /**
  74279. * Disposes each of the internal effects for a given camera.
  74280. * @param camera The camera to dispose the effect on.
  74281. */
  74282. BloomEffect.prototype.disposeEffects = function (camera) {
  74283. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74284. this._effects[effectIndex].dispose(camera);
  74285. }
  74286. };
  74287. /**
  74288. * Internal
  74289. */
  74290. BloomEffect.prototype._updateEffects = function () {
  74291. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74292. this._effects[effectIndex].updateEffect();
  74293. }
  74294. };
  74295. /**
  74296. * Internal
  74297. * @returns if all the contained post processes are ready.
  74298. */
  74299. BloomEffect.prototype._isReady = function () {
  74300. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74301. if (!this._effects[effectIndex].isReady()) {
  74302. return false;
  74303. }
  74304. }
  74305. return true;
  74306. };
  74307. return BloomEffect;
  74308. }(BABYLON.PostProcessRenderEffect));
  74309. BABYLON.BloomEffect = BloomEffect;
  74310. })(BABYLON || (BABYLON = {}));
  74311. //# sourceMappingURL=babylon.bloomEffect.js.map
  74312. "use strict";
  74313. var BABYLON;
  74314. (function (BABYLON) {
  74315. /**
  74316. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74317. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74318. */
  74319. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74320. __extends(DefaultRenderingPipeline, _super);
  74321. /**
  74322. * @constructor
  74323. * @param {string} name - The rendering pipeline name
  74324. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74325. * @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)
  74326. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74327. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74328. */
  74329. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74330. if (automaticBuild === void 0) { automaticBuild = true; }
  74331. var _this = _super.call(this, scene.getEngine(), name) || this;
  74332. _this._originalCameras = [];
  74333. /**
  74334. * ID of the sharpen post process,
  74335. */
  74336. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74337. /**
  74338. * ID of the image processing post process;
  74339. */
  74340. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74341. /**
  74342. * ID of the Fast Approximate Anti-Aliasing post process;
  74343. */
  74344. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74345. /**
  74346. * ID of the chromatic aberration post process,
  74347. */
  74348. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74349. /**
  74350. * ID of the grain post process
  74351. */
  74352. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74353. /**
  74354. * Animations which can be used to tweak settings over a period of time
  74355. */
  74356. _this.animations = [];
  74357. _this._imageProcessingConfigurationObserver = null;
  74358. // Values
  74359. _this._sharpenEnabled = false;
  74360. _this._bloomEnabled = false;
  74361. _this._depthOfFieldEnabled = false;
  74362. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74363. _this._fxaaEnabled = false;
  74364. _this._imageProcessingEnabled = true;
  74365. _this._bloomScale = 0.5;
  74366. _this._chromaticAberrationEnabled = false;
  74367. _this._grainEnabled = false;
  74368. _this._buildAllowed = true;
  74369. _this._resizeObserver = null;
  74370. _this._hardwareScaleLevel = 1.0;
  74371. _this._bloomKernel = 64;
  74372. /**
  74373. * Specifies the weight of the bloom in the final rendering
  74374. */
  74375. _this._bloomWeight = 0.15;
  74376. /**
  74377. * Specifies the luma threshold for the area that will be blurred by the bloom
  74378. */
  74379. _this._bloomThreshold = 0.9;
  74380. _this._samples = 1;
  74381. _this._hasCleared = false;
  74382. _this._prevPostProcess = null;
  74383. _this._prevPrevPostProcess = null;
  74384. _this._cameras = cameras || [];
  74385. _this._originalCameras = _this._cameras.slice();
  74386. _this._buildAllowed = automaticBuild;
  74387. // Initialize
  74388. _this._scene = scene;
  74389. var caps = _this._scene.getEngine().getCaps();
  74390. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74391. // Misc
  74392. if (_this._hdr) {
  74393. if (caps.textureHalfFloatRender) {
  74394. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74395. }
  74396. else if (caps.textureFloatRender) {
  74397. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74398. }
  74399. }
  74400. else {
  74401. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74402. }
  74403. // Attach
  74404. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74405. var engine = _this._scene.getEngine();
  74406. // Create post processes before hand so they can be modified before enabled.
  74407. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74408. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74409. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74410. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74411. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74412. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74413. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74414. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74415. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74416. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74417. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74418. _this.bloomKernel = _this.bloomKernel;
  74419. });
  74420. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74421. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74422. });
  74423. _this._buildPipeline();
  74424. return _this;
  74425. }
  74426. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74427. get: function () {
  74428. return this._sharpenEnabled;
  74429. },
  74430. /**
  74431. * Enable or disable the sharpen process from the pipeline
  74432. */
  74433. set: function (enabled) {
  74434. if (this._sharpenEnabled === enabled) {
  74435. return;
  74436. }
  74437. this._sharpenEnabled = enabled;
  74438. this._buildPipeline();
  74439. },
  74440. enumerable: true,
  74441. configurable: true
  74442. });
  74443. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74444. /**
  74445. * Specifies the size of the bloom blur kernel, relative to the final output size
  74446. */
  74447. get: function () {
  74448. return this._bloomKernel;
  74449. },
  74450. set: function (value) {
  74451. this._bloomKernel = value;
  74452. this.bloom.kernel = value / this._hardwareScaleLevel;
  74453. },
  74454. enumerable: true,
  74455. configurable: true
  74456. });
  74457. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74458. get: function () {
  74459. return this._bloomWeight;
  74460. },
  74461. /**
  74462. * The strength of the bloom.
  74463. */
  74464. set: function (value) {
  74465. if (this._bloomWeight === value) {
  74466. return;
  74467. }
  74468. this.bloom.weight = value;
  74469. this._bloomWeight = value;
  74470. },
  74471. enumerable: true,
  74472. configurable: true
  74473. });
  74474. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74475. get: function () {
  74476. return this._bloomThreshold;
  74477. },
  74478. /**
  74479. * The strength of the bloom.
  74480. */
  74481. set: function (value) {
  74482. if (this._bloomThreshold === value) {
  74483. return;
  74484. }
  74485. this.bloom.threshold = value;
  74486. this._bloomThreshold = value;
  74487. },
  74488. enumerable: true,
  74489. configurable: true
  74490. });
  74491. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74492. get: function () {
  74493. return this._bloomScale;
  74494. },
  74495. /**
  74496. * The scale of the bloom, lower value will provide better performance.
  74497. */
  74498. set: function (value) {
  74499. if (this._bloomScale === value) {
  74500. return;
  74501. }
  74502. this._bloomScale = value;
  74503. // recreate bloom and dispose old as this setting is not dynamic
  74504. this._rebuildBloom();
  74505. this._buildPipeline();
  74506. },
  74507. enumerable: true,
  74508. configurable: true
  74509. });
  74510. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  74511. get: function () {
  74512. return this._bloomEnabled;
  74513. },
  74514. /**
  74515. * Enable or disable the bloom from the pipeline
  74516. */
  74517. set: function (enabled) {
  74518. if (this._bloomEnabled === enabled) {
  74519. return;
  74520. }
  74521. this._bloomEnabled = enabled;
  74522. this._buildPipeline();
  74523. },
  74524. enumerable: true,
  74525. configurable: true
  74526. });
  74527. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  74528. // recreate bloom and dispose old as this setting is not dynamic
  74529. var oldBloom = this.bloom;
  74530. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  74531. this.bloom.threshold = oldBloom.threshold;
  74532. for (var i = 0; i < this._cameras.length; i++) {
  74533. oldBloom.disposeEffects(this._cameras[i]);
  74534. }
  74535. };
  74536. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74537. /**
  74538. * If the depth of field is enabled.
  74539. */
  74540. get: function () {
  74541. return this._depthOfFieldEnabled;
  74542. },
  74543. set: function (enabled) {
  74544. if (this._depthOfFieldEnabled === enabled) {
  74545. return;
  74546. }
  74547. this._depthOfFieldEnabled = enabled;
  74548. this._buildPipeline();
  74549. },
  74550. enumerable: true,
  74551. configurable: true
  74552. });
  74553. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  74554. /**
  74555. * Blur level of the depth of field effect. (Higher blur will effect performance)
  74556. */
  74557. get: function () {
  74558. return this._depthOfFieldBlurLevel;
  74559. },
  74560. set: function (value) {
  74561. if (this._depthOfFieldBlurLevel === value) {
  74562. return;
  74563. }
  74564. this._depthOfFieldBlurLevel = value;
  74565. // recreate dof and dispose old as this setting is not dynamic
  74566. var oldDof = this.depthOfField;
  74567. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74568. this.depthOfField.focalLength = oldDof.focalLength;
  74569. this.depthOfField.focusDistance = oldDof.focusDistance;
  74570. this.depthOfField.fStop = oldDof.fStop;
  74571. this.depthOfField.lensSize = oldDof.lensSize;
  74572. for (var i = 0; i < this._cameras.length; i++) {
  74573. oldDof.disposeEffects(this._cameras[i]);
  74574. }
  74575. this._buildPipeline();
  74576. },
  74577. enumerable: true,
  74578. configurable: true
  74579. });
  74580. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74581. get: function () {
  74582. return this._fxaaEnabled;
  74583. },
  74584. /**
  74585. * If the anti aliasing is enabled.
  74586. */
  74587. set: function (enabled) {
  74588. if (this._fxaaEnabled === enabled) {
  74589. return;
  74590. }
  74591. this._fxaaEnabled = enabled;
  74592. this._buildPipeline();
  74593. },
  74594. enumerable: true,
  74595. configurable: true
  74596. });
  74597. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74598. get: function () {
  74599. return this._samples;
  74600. },
  74601. /**
  74602. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74603. */
  74604. set: function (sampleCount) {
  74605. if (this._samples === sampleCount) {
  74606. return;
  74607. }
  74608. this._samples = sampleCount;
  74609. this._buildPipeline();
  74610. },
  74611. enumerable: true,
  74612. configurable: true
  74613. });
  74614. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74615. get: function () {
  74616. return this._imageProcessingEnabled;
  74617. },
  74618. /**
  74619. * If image processing is enabled.
  74620. */
  74621. set: function (enabled) {
  74622. if (this._imageProcessingEnabled === enabled) {
  74623. return;
  74624. }
  74625. this._imageProcessingEnabled = enabled;
  74626. this._buildPipeline();
  74627. },
  74628. enumerable: true,
  74629. configurable: true
  74630. });
  74631. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74632. get: function () {
  74633. return this._chromaticAberrationEnabled;
  74634. },
  74635. /**
  74636. * Enable or disable the chromaticAberration process from the pipeline
  74637. */
  74638. set: function (enabled) {
  74639. if (this._chromaticAberrationEnabled === enabled) {
  74640. return;
  74641. }
  74642. this._chromaticAberrationEnabled = enabled;
  74643. this._buildPipeline();
  74644. },
  74645. enumerable: true,
  74646. configurable: true
  74647. });
  74648. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  74649. get: function () {
  74650. return this._grainEnabled;
  74651. },
  74652. /**
  74653. * Enable or disable the grain process from the pipeline
  74654. */
  74655. set: function (enabled) {
  74656. if (this._grainEnabled === enabled) {
  74657. return;
  74658. }
  74659. this._grainEnabled = enabled;
  74660. this._buildPipeline();
  74661. },
  74662. enumerable: true,
  74663. configurable: true
  74664. });
  74665. /**
  74666. * Force the compilation of the entire pipeline.
  74667. */
  74668. DefaultRenderingPipeline.prototype.prepare = function () {
  74669. var previousState = this._buildAllowed;
  74670. this._buildAllowed = true;
  74671. this._buildPipeline();
  74672. this._buildAllowed = previousState;
  74673. };
  74674. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  74675. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  74676. if (this._hasCleared) {
  74677. postProcess.autoClear = false;
  74678. }
  74679. else {
  74680. postProcess.autoClear = true;
  74681. this._scene.autoClear = false;
  74682. this._hasCleared = true;
  74683. }
  74684. if (!skipTextureSharing) {
  74685. if (this._prevPrevPostProcess) {
  74686. postProcess.shareOutputWith(this._prevPrevPostProcess);
  74687. }
  74688. else {
  74689. postProcess.useOwnOutput();
  74690. }
  74691. if (this._prevPostProcess) {
  74692. this._prevPrevPostProcess = this._prevPostProcess;
  74693. }
  74694. this._prevPostProcess = postProcess;
  74695. }
  74696. };
  74697. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  74698. var _this = this;
  74699. if (!this._buildAllowed) {
  74700. return;
  74701. }
  74702. this._scene.autoClear = true;
  74703. var engine = this._scene.getEngine();
  74704. this._disposePostProcesses();
  74705. if (this._cameras !== null) {
  74706. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74707. // get back cameras to be used to reattach pipeline
  74708. this._cameras = this._originalCameras.slice();
  74709. }
  74710. this._reset();
  74711. this._prevPostProcess = null;
  74712. this._prevPrevPostProcess = null;
  74713. this._hasCleared = false;
  74714. if (this.depthOfFieldEnabled) {
  74715. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  74716. this.depthOfField.depthTexture = depthTexture;
  74717. if (!this.depthOfField._isReady()) {
  74718. this.depthOfField._updateEffects();
  74719. }
  74720. this.addEffect(this.depthOfField);
  74721. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  74722. }
  74723. if (this.bloomEnabled) {
  74724. if (!this.bloom._isReady()) {
  74725. this.bloom._updateEffects();
  74726. }
  74727. this.addEffect(this.bloom);
  74728. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  74729. }
  74730. if (this._imageProcessingEnabled) {
  74731. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74732. if (this._hdr) {
  74733. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  74734. this._setAutoClearAndTextureSharing(this.imageProcessing);
  74735. }
  74736. else {
  74737. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  74738. }
  74739. }
  74740. if (this.sharpenEnabled) {
  74741. if (!this.sharpen.isReady()) {
  74742. this.sharpen.updateEffect();
  74743. }
  74744. this.addEffect(this._sharpenEffect);
  74745. this._setAutoClearAndTextureSharing(this.sharpen);
  74746. }
  74747. if (this.grainEnabled) {
  74748. if (!this.grain.isReady()) {
  74749. this.grain.updateEffect();
  74750. }
  74751. this.addEffect(this._grainEffect);
  74752. this._setAutoClearAndTextureSharing(this.grain);
  74753. }
  74754. if (this.chromaticAberrationEnabled) {
  74755. if (!this.chromaticAberration.isReady()) {
  74756. this.chromaticAberration.updateEffect();
  74757. }
  74758. this.addEffect(this._chromaticAberrationEffect);
  74759. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  74760. }
  74761. if (this.fxaaEnabled) {
  74762. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74763. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  74764. this._setAutoClearAndTextureSharing(this.fxaa, true);
  74765. }
  74766. if (this._cameras !== null) {
  74767. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74768. }
  74769. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  74770. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  74771. }
  74772. };
  74773. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  74774. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  74775. for (var i = 0; i < this._cameras.length; i++) {
  74776. var camera = this._cameras[i];
  74777. if (this.imageProcessing) {
  74778. this.imageProcessing.dispose(camera);
  74779. }
  74780. if (this.fxaa) {
  74781. this.fxaa.dispose(camera);
  74782. }
  74783. // These are created in the constructor and should not be disposed on every pipeline change
  74784. if (disposeNonRecreated) {
  74785. if (this.sharpen) {
  74786. this.sharpen.dispose(camera);
  74787. }
  74788. if (this.depthOfField) {
  74789. this.depthOfField.disposeEffects(camera);
  74790. }
  74791. if (this.bloom) {
  74792. this.bloom.disposeEffects(camera);
  74793. }
  74794. if (this.chromaticAberration) {
  74795. this.chromaticAberration.dispose(camera);
  74796. }
  74797. if (this.grain) {
  74798. this.grain.dispose(camera);
  74799. }
  74800. }
  74801. }
  74802. this.imageProcessing = null;
  74803. this.fxaa = null;
  74804. if (disposeNonRecreated) {
  74805. this.sharpen = null;
  74806. this._sharpenEffect = null;
  74807. this.depthOfField = null;
  74808. this.bloom = null;
  74809. this.chromaticAberration = null;
  74810. this._chromaticAberrationEffect = null;
  74811. this.grain = null;
  74812. this._grainEffect = null;
  74813. }
  74814. };
  74815. /**
  74816. * Dispose of the pipeline and stop all post processes
  74817. */
  74818. DefaultRenderingPipeline.prototype.dispose = function () {
  74819. this._disposePostProcesses(true);
  74820. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74821. this._scene.autoClear = true;
  74822. if (this._resizeObserver) {
  74823. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  74824. this._resizeObserver = null;
  74825. }
  74826. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  74827. _super.prototype.dispose.call(this);
  74828. };
  74829. /**
  74830. * Serialize the rendering pipeline (Used when exporting)
  74831. * @returns the serialized object
  74832. */
  74833. DefaultRenderingPipeline.prototype.serialize = function () {
  74834. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74835. serializationObject.customType = "DefaultRenderingPipeline";
  74836. return serializationObject;
  74837. };
  74838. /**
  74839. * Parse the serialized pipeline
  74840. * @param source Source pipeline.
  74841. * @param scene The scene to load the pipeline to.
  74842. * @param rootUrl The URL of the serialized pipeline.
  74843. * @returns An instantiated pipeline from the serialized object.
  74844. */
  74845. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74846. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  74847. };
  74848. __decorate([
  74849. BABYLON.serialize()
  74850. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  74851. __decorate([
  74852. BABYLON.serialize()
  74853. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  74854. __decorate([
  74855. BABYLON.serialize()
  74856. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  74857. __decorate([
  74858. BABYLON.serialize()
  74859. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  74860. __decorate([
  74861. BABYLON.serialize()
  74862. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  74863. __decorate([
  74864. BABYLON.serialize()
  74865. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  74866. __decorate([
  74867. BABYLON.serialize()
  74868. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  74869. __decorate([
  74870. BABYLON.serialize()
  74871. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  74872. __decorate([
  74873. BABYLON.serialize()
  74874. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  74875. __decorate([
  74876. BABYLON.serialize()
  74877. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  74878. __decorate([
  74879. BABYLON.serialize()
  74880. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  74881. __decorate([
  74882. BABYLON.serialize()
  74883. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  74884. __decorate([
  74885. BABYLON.serialize()
  74886. ], DefaultRenderingPipeline.prototype, "samples", null);
  74887. __decorate([
  74888. BABYLON.serialize()
  74889. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  74890. __decorate([
  74891. BABYLON.serialize()
  74892. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  74893. __decorate([
  74894. BABYLON.serialize()
  74895. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  74896. return DefaultRenderingPipeline;
  74897. }(BABYLON.PostProcessRenderPipeline));
  74898. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  74899. })(BABYLON || (BABYLON = {}));
  74900. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  74901. "use strict";
  74902. var BABYLON;
  74903. (function (BABYLON) {
  74904. /**
  74905. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  74906. */
  74907. var GeometryBufferRenderer = /** @class */ (function () {
  74908. /**
  74909. * Creates a new G Buffer for the scene
  74910. * @param scene The scene the buffer belongs to
  74911. * @param ratio How big is the buffer related to the main canvas.
  74912. */
  74913. function GeometryBufferRenderer(scene, ratio) {
  74914. if (ratio === void 0) { ratio = 1; }
  74915. this._enablePosition = false;
  74916. this._scene = scene;
  74917. this._ratio = ratio;
  74918. // Render target
  74919. this._createRenderTargets();
  74920. }
  74921. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  74922. /**
  74923. * Set the render list (meshes to be rendered) used in the G buffer.
  74924. */
  74925. set: function (meshes) {
  74926. this._multiRenderTarget.renderList = meshes;
  74927. },
  74928. enumerable: true,
  74929. configurable: true
  74930. });
  74931. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  74932. /**
  74933. * Gets wether or not G buffer are supported by the running hardware.
  74934. * This requires draw buffer supports
  74935. */
  74936. get: function () {
  74937. return this._multiRenderTarget.isSupported;
  74938. },
  74939. enumerable: true,
  74940. configurable: true
  74941. });
  74942. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  74943. /**
  74944. * Gets wether or not position are enabled for the G buffer.
  74945. */
  74946. get: function () {
  74947. return this._enablePosition;
  74948. },
  74949. /**
  74950. * Sets wether or not position are enabled for the G buffer.
  74951. */
  74952. set: function (enable) {
  74953. this._enablePosition = enable;
  74954. this.dispose();
  74955. this._createRenderTargets();
  74956. },
  74957. enumerable: true,
  74958. configurable: true
  74959. });
  74960. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  74961. /**
  74962. * Gets the scene associated with the buffer.
  74963. */
  74964. get: function () {
  74965. return this._scene;
  74966. },
  74967. enumerable: true,
  74968. configurable: true
  74969. });
  74970. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  74971. /**
  74972. * Gets the ratio used by the buffer during its creation.
  74973. * How big is the buffer related to the main canvas.
  74974. */
  74975. get: function () {
  74976. return this._ratio;
  74977. },
  74978. enumerable: true,
  74979. configurable: true
  74980. });
  74981. /**
  74982. * Checks wether everything is ready to render a submesh to the G buffer.
  74983. * @param subMesh the submesh to check readiness for
  74984. * @param useInstances is the mesh drawn using instance or not
  74985. * @returns true if ready otherwise false
  74986. */
  74987. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  74988. var material = subMesh.getMaterial();
  74989. if (material && material.disableDepthWrite) {
  74990. return false;
  74991. }
  74992. var defines = [];
  74993. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74994. var mesh = subMesh.getMesh();
  74995. // Alpha test
  74996. if (material && material.needAlphaTesting()) {
  74997. defines.push("#define ALPHATEST");
  74998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74999. attribs.push(BABYLON.VertexBuffer.UVKind);
  75000. defines.push("#define UV1");
  75001. }
  75002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75003. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75004. defines.push("#define UV2");
  75005. }
  75006. }
  75007. // Buffers
  75008. if (this._enablePosition) {
  75009. defines.push("#define POSITION");
  75010. }
  75011. // Bones
  75012. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75013. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75014. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75015. if (mesh.numBoneInfluencers > 4) {
  75016. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75017. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75018. }
  75019. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75020. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75021. }
  75022. else {
  75023. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75024. }
  75025. // Instances
  75026. if (useInstances) {
  75027. defines.push("#define INSTANCES");
  75028. attribs.push("world0");
  75029. attribs.push("world1");
  75030. attribs.push("world2");
  75031. attribs.push("world3");
  75032. }
  75033. // Get correct effect
  75034. var join = defines.join("\n");
  75035. if (this._cachedDefines !== join) {
  75036. this._cachedDefines = join;
  75037. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75038. }
  75039. return this._effect.isReady();
  75040. };
  75041. /**
  75042. * Gets the current underlying G Buffer.
  75043. * @returns the buffer
  75044. */
  75045. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75046. return this._multiRenderTarget;
  75047. };
  75048. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75049. /**
  75050. * Gets the number of samples used to render the buffer (anti aliasing).
  75051. */
  75052. get: function () {
  75053. return this._multiRenderTarget.samples;
  75054. },
  75055. /**
  75056. * Sets the number of samples used to render the buffer (anti aliasing).
  75057. */
  75058. set: function (value) {
  75059. this._multiRenderTarget.samples = value;
  75060. },
  75061. enumerable: true,
  75062. configurable: true
  75063. });
  75064. /**
  75065. * Disposes the renderer and frees up associated resources.
  75066. */
  75067. GeometryBufferRenderer.prototype.dispose = function () {
  75068. this.getGBuffer().dispose();
  75069. };
  75070. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75071. var _this = this;
  75072. var engine = this._scene.getEngine();
  75073. var count = this._enablePosition ? 3 : 2;
  75074. 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 });
  75075. if (!this.isSupported) {
  75076. return;
  75077. }
  75078. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75079. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75080. this._multiRenderTarget.refreshRate = 1;
  75081. this._multiRenderTarget.renderParticles = false;
  75082. this._multiRenderTarget.renderList = null;
  75083. // set default depth value to 1.0 (far away)
  75084. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75085. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75086. });
  75087. // Custom render function
  75088. var renderSubMesh = function (subMesh) {
  75089. var mesh = subMesh.getRenderingMesh();
  75090. var scene = _this._scene;
  75091. var engine = scene.getEngine();
  75092. var material = subMesh.getMaterial();
  75093. if (!material) {
  75094. return;
  75095. }
  75096. // Culling
  75097. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75098. // Managing instances
  75099. var batch = mesh._getInstancesRenderList(subMesh._id);
  75100. if (batch.mustReturn) {
  75101. return;
  75102. }
  75103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75104. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75105. engine.enableEffect(_this._effect);
  75106. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75107. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75108. _this._effect.setMatrix("view", scene.getViewMatrix());
  75109. // Alpha test
  75110. if (material && material.needAlphaTesting()) {
  75111. var alphaTexture = material.getAlphaTestTexture();
  75112. if (alphaTexture) {
  75113. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75114. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75115. }
  75116. }
  75117. // Bones
  75118. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75119. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75120. }
  75121. // Draw
  75122. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75123. }
  75124. };
  75125. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75126. var index;
  75127. if (depthOnlySubMeshes.length) {
  75128. engine.setColorWrite(false);
  75129. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75130. renderSubMesh(depthOnlySubMeshes.data[index]);
  75131. }
  75132. engine.setColorWrite(true);
  75133. }
  75134. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75135. renderSubMesh(opaqueSubMeshes.data[index]);
  75136. }
  75137. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75138. renderSubMesh(alphaTestSubMeshes.data[index]);
  75139. }
  75140. };
  75141. };
  75142. return GeometryBufferRenderer;
  75143. }());
  75144. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75145. })(BABYLON || (BABYLON = {}));
  75146. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75147. "use strict";
  75148. var BABYLON;
  75149. (function (BABYLON) {
  75150. var RefractionPostProcess = /** @class */ (function (_super) {
  75151. __extends(RefractionPostProcess, _super);
  75152. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  75153. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  75154. _this.color = color;
  75155. _this.depth = depth;
  75156. _this.colorLevel = colorLevel;
  75157. _this._ownRefractionTexture = true;
  75158. _this.onActivateObservable.add(function (cam) {
  75159. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  75160. });
  75161. _this.onApplyObservable.add(function (effect) {
  75162. effect.setColor3("baseColor", _this.color);
  75163. effect.setFloat("depth", _this.depth);
  75164. effect.setFloat("colorLevel", _this.colorLevel);
  75165. effect.setTexture("refractionSampler", _this._refTexture);
  75166. });
  75167. return _this;
  75168. }
  75169. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  75170. /**
  75171. * Gets or sets the refraction texture
  75172. * Please note that you are responsible for disposing the texture if you set it manually
  75173. */
  75174. get: function () {
  75175. return this._refTexture;
  75176. },
  75177. set: function (value) {
  75178. if (this._refTexture && this._ownRefractionTexture) {
  75179. this._refTexture.dispose();
  75180. }
  75181. this._refTexture = value;
  75182. this._ownRefractionTexture = false;
  75183. },
  75184. enumerable: true,
  75185. configurable: true
  75186. });
  75187. // Methods
  75188. RefractionPostProcess.prototype.dispose = function (camera) {
  75189. if (this._refTexture && this._ownRefractionTexture) {
  75190. this._refTexture.dispose();
  75191. this._refTexture = null;
  75192. }
  75193. _super.prototype.dispose.call(this, camera);
  75194. };
  75195. return RefractionPostProcess;
  75196. }(BABYLON.PostProcess));
  75197. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75198. })(BABYLON || (BABYLON = {}));
  75199. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75200. "use strict";
  75201. var BABYLON;
  75202. (function (BABYLON) {
  75203. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75204. __extends(BlackAndWhitePostProcess, _super);
  75205. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75206. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75207. _this.degree = 1;
  75208. _this.onApplyObservable.add(function (effect) {
  75209. effect.setFloat("degree", _this.degree);
  75210. });
  75211. return _this;
  75212. }
  75213. return BlackAndWhitePostProcess;
  75214. }(BABYLON.PostProcess));
  75215. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75216. })(BABYLON || (BABYLON = {}));
  75217. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75218. "use strict";
  75219. var BABYLON;
  75220. (function (BABYLON) {
  75221. /**
  75222. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75223. * input texture to perform effects such as edge detection or sharpening
  75224. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75225. */
  75226. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75227. __extends(ConvolutionPostProcess, _super);
  75228. /**
  75229. * Creates a new instance ConvolutionPostProcess
  75230. * @param name The name of the effect.
  75231. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75232. * @param options The required width/height ratio to downsize to before computing the render pass.
  75233. * @param camera The camera to apply the render pass to.
  75234. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75235. * @param engine The engine which the post process will be applied. (default: current engine)
  75236. * @param reusable If the post process can be reused on the same frame. (default: false)
  75237. * @param textureType Type of textures used when performing the post process. (default: 0)
  75238. */
  75239. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75240. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75241. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75242. _this.kernel = kernel;
  75243. _this.onApply = function (effect) {
  75244. effect.setFloat2("screenSize", _this.width, _this.height);
  75245. effect.setArray("kernel", _this.kernel);
  75246. };
  75247. return _this;
  75248. }
  75249. // Statics
  75250. /**
  75251. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75252. */
  75253. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75254. /**
  75255. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75256. */
  75257. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75258. /**
  75259. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75260. */
  75261. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75262. /**
  75263. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75264. */
  75265. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75266. /**
  75267. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75268. */
  75269. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75270. /**
  75271. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75272. */
  75273. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75274. return ConvolutionPostProcess;
  75275. }(BABYLON.PostProcess));
  75276. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75277. })(BABYLON || (BABYLON = {}));
  75278. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75279. "use strict";
  75280. var BABYLON;
  75281. (function (BABYLON) {
  75282. var FilterPostProcess = /** @class */ (function (_super) {
  75283. __extends(FilterPostProcess, _super);
  75284. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75285. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75286. _this.kernelMatrix = kernelMatrix;
  75287. _this.onApply = function (effect) {
  75288. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75289. };
  75290. return _this;
  75291. }
  75292. return FilterPostProcess;
  75293. }(BABYLON.PostProcess));
  75294. BABYLON.FilterPostProcess = FilterPostProcess;
  75295. })(BABYLON || (BABYLON = {}));
  75296. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75297. "use strict";
  75298. var BABYLON;
  75299. (function (BABYLON) {
  75300. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75301. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75302. __extends(VolumetricLightScatteringPostProcess, _super);
  75303. /**
  75304. * @constructor
  75305. * @param {string} name - The post-process name
  75306. * @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)
  75307. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75308. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75309. * @param {number} samples - The post-process quality, default 100
  75310. * @param {number} samplingMode - The post-process filtering mode
  75311. * @param {BABYLON.Engine} engine - The babylon engine
  75312. * @param {boolean} reusable - If the post-process is reusable
  75313. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75314. */
  75315. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75316. if (samples === void 0) { samples = 100; }
  75317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75318. 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;
  75319. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75320. /**
  75321. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75322. */
  75323. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75324. /**
  75325. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75326. */
  75327. _this.useCustomMeshPosition = false;
  75328. /**
  75329. * If the post-process should inverse the light scattering direction
  75330. */
  75331. _this.invert = true;
  75332. /**
  75333. * Array containing the excluded meshes not rendered in the internal pass
  75334. */
  75335. _this.excludedMeshes = new Array();
  75336. /**
  75337. * Controls the overall intensity of the post-process
  75338. */
  75339. _this.exposure = 0.3;
  75340. /**
  75341. * Dissipates each sample's contribution in range [0, 1]
  75342. */
  75343. _this.decay = 0.96815;
  75344. /**
  75345. * Controls the overall intensity of each sample
  75346. */
  75347. _this.weight = 0.58767;
  75348. /**
  75349. * Controls the density of each sample
  75350. */
  75351. _this.density = 0.926;
  75352. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75353. engine = scene.getEngine();
  75354. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75355. // Configure mesh
  75356. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75357. // Configure
  75358. _this._createPass(scene, ratio.passRatio || ratio);
  75359. _this.onActivate = function (camera) {
  75360. if (!_this.isSupported) {
  75361. _this.dispose(camera);
  75362. }
  75363. _this.onActivate = null;
  75364. };
  75365. _this.onApplyObservable.add(function (effect) {
  75366. _this._updateMeshScreenCoordinates(scene);
  75367. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75368. effect.setFloat("exposure", _this.exposure);
  75369. effect.setFloat("decay", _this.decay);
  75370. effect.setFloat("weight", _this.weight);
  75371. effect.setFloat("density", _this.density);
  75372. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75373. });
  75374. return _this;
  75375. }
  75376. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75377. get: function () {
  75378. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75379. return false;
  75380. },
  75381. set: function (useDiffuseColor) {
  75382. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75383. },
  75384. enumerable: true,
  75385. configurable: true
  75386. });
  75387. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75388. return "VolumetricLightScatteringPostProcess";
  75389. };
  75390. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75391. var mesh = subMesh.getMesh();
  75392. // Render this.mesh as default
  75393. if (mesh === this.mesh && mesh.material) {
  75394. return mesh.material.isReady(mesh);
  75395. }
  75396. var defines = [];
  75397. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75398. var material = subMesh.getMaterial();
  75399. // Alpha test
  75400. if (material) {
  75401. if (material.needAlphaTesting()) {
  75402. defines.push("#define ALPHATEST");
  75403. }
  75404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75405. attribs.push(BABYLON.VertexBuffer.UVKind);
  75406. defines.push("#define UV1");
  75407. }
  75408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75409. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75410. defines.push("#define UV2");
  75411. }
  75412. }
  75413. // Bones
  75414. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75415. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75416. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75417. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75418. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75419. }
  75420. else {
  75421. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75422. }
  75423. // Instances
  75424. if (useInstances) {
  75425. defines.push("#define INSTANCES");
  75426. attribs.push("world0");
  75427. attribs.push("world1");
  75428. attribs.push("world2");
  75429. attribs.push("world3");
  75430. }
  75431. // Get correct effect
  75432. var join = defines.join("\n");
  75433. if (this._cachedDefines !== join) {
  75434. this._cachedDefines = join;
  75435. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75436. }
  75437. return this._volumetricLightScatteringPass.isReady();
  75438. };
  75439. /**
  75440. * Sets the new light position for light scattering effect
  75441. * @param {BABYLON.Vector3} The new custom light position
  75442. */
  75443. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75444. this.customMeshPosition = position;
  75445. };
  75446. /**
  75447. * Returns the light position for light scattering effect
  75448. * @return {BABYLON.Vector3} The custom light position
  75449. */
  75450. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75451. return this.customMeshPosition;
  75452. };
  75453. /**
  75454. * Disposes the internal assets and detaches the post-process from the camera
  75455. */
  75456. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75457. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75458. if (rttIndex !== -1) {
  75459. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75460. }
  75461. this._volumetricLightScatteringRTT.dispose();
  75462. _super.prototype.dispose.call(this, camera);
  75463. };
  75464. /**
  75465. * Returns the render target texture used by the post-process
  75466. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75467. */
  75468. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75469. return this._volumetricLightScatteringRTT;
  75470. };
  75471. // Private methods
  75472. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75473. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75474. return true;
  75475. }
  75476. return false;
  75477. };
  75478. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75479. var _this = this;
  75480. var engine = scene.getEngine();
  75481. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75482. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75483. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75484. this._volumetricLightScatteringRTT.renderList = null;
  75485. this._volumetricLightScatteringRTT.renderParticles = false;
  75486. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75487. var camera = this.getCamera();
  75488. if (camera) {
  75489. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75490. }
  75491. else {
  75492. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75493. }
  75494. // Custom render function for submeshes
  75495. var renderSubMesh = function (subMesh) {
  75496. var mesh = subMesh.getRenderingMesh();
  75497. if (_this._meshExcluded(mesh)) {
  75498. return;
  75499. }
  75500. var material = subMesh.getMaterial();
  75501. if (!material) {
  75502. return;
  75503. }
  75504. var scene = mesh.getScene();
  75505. var engine = scene.getEngine();
  75506. // Culling
  75507. engine.setState(material.backFaceCulling);
  75508. // Managing instances
  75509. var batch = mesh._getInstancesRenderList(subMesh._id);
  75510. if (batch.mustReturn) {
  75511. return;
  75512. }
  75513. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75514. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  75515. var effect = _this._volumetricLightScatteringPass;
  75516. if (mesh === _this.mesh) {
  75517. if (subMesh.effect) {
  75518. effect = subMesh.effect;
  75519. }
  75520. else {
  75521. effect = material.getEffect();
  75522. }
  75523. }
  75524. engine.enableEffect(effect);
  75525. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  75526. if (mesh === _this.mesh) {
  75527. material.bind(mesh.getWorldMatrix(), mesh);
  75528. }
  75529. else {
  75530. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  75531. // Alpha test
  75532. if (material && material.needAlphaTesting()) {
  75533. var alphaTexture = material.getAlphaTestTexture();
  75534. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  75535. if (alphaTexture) {
  75536. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75537. }
  75538. }
  75539. // Bones
  75540. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75541. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75542. }
  75543. }
  75544. // Draw
  75545. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  75546. }
  75547. };
  75548. // Render target texture callbacks
  75549. var savedSceneClearColor;
  75550. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  75551. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  75552. savedSceneClearColor = scene.clearColor;
  75553. scene.clearColor = sceneClearColor;
  75554. });
  75555. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  75556. scene.clearColor = savedSceneClearColor;
  75557. });
  75558. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75559. var engine = scene.getEngine();
  75560. var index;
  75561. if (depthOnlySubMeshes.length) {
  75562. engine.setColorWrite(false);
  75563. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75564. renderSubMesh(depthOnlySubMeshes.data[index]);
  75565. }
  75566. engine.setColorWrite(true);
  75567. }
  75568. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75569. renderSubMesh(opaqueSubMeshes.data[index]);
  75570. }
  75571. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75572. renderSubMesh(alphaTestSubMeshes.data[index]);
  75573. }
  75574. if (transparentSubMeshes.length) {
  75575. // Sort sub meshes
  75576. for (index = 0; index < transparentSubMeshes.length; index++) {
  75577. var submesh = transparentSubMeshes.data[index];
  75578. var boundingInfo = submesh.getBoundingInfo();
  75579. if (boundingInfo && scene.activeCamera) {
  75580. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75581. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75582. }
  75583. }
  75584. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75585. sortedArray.sort(function (a, b) {
  75586. // Alpha index first
  75587. if (a._alphaIndex > b._alphaIndex) {
  75588. return 1;
  75589. }
  75590. if (a._alphaIndex < b._alphaIndex) {
  75591. return -1;
  75592. }
  75593. // Then distance to camera
  75594. if (a._distanceToCamera < b._distanceToCamera) {
  75595. return 1;
  75596. }
  75597. if (a._distanceToCamera > b._distanceToCamera) {
  75598. return -1;
  75599. }
  75600. return 0;
  75601. });
  75602. // Render sub meshes
  75603. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75604. for (index = 0; index < sortedArray.length; index++) {
  75605. renderSubMesh(sortedArray[index]);
  75606. }
  75607. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75608. }
  75609. };
  75610. };
  75611. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75612. var transform = scene.getTransformMatrix();
  75613. var meshPosition;
  75614. if (this.useCustomMeshPosition) {
  75615. meshPosition = this.customMeshPosition;
  75616. }
  75617. else if (this.attachedNode) {
  75618. meshPosition = this.attachedNode.position;
  75619. }
  75620. else {
  75621. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75622. }
  75623. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75624. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75625. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75626. if (this.invert)
  75627. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75628. };
  75629. // Static methods
  75630. /**
  75631. * Creates a default mesh for the Volumeric Light Scattering post-process
  75632. * @param {string} The mesh name
  75633. * @param {BABYLON.Scene} The scene where to create the mesh
  75634. * @return {BABYLON.Mesh} the default mesh
  75635. */
  75636. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75637. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75638. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75639. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75640. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75641. mesh.material = material;
  75642. return mesh;
  75643. };
  75644. __decorate([
  75645. BABYLON.serializeAsVector3()
  75646. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  75647. __decorate([
  75648. BABYLON.serialize()
  75649. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  75650. __decorate([
  75651. BABYLON.serialize()
  75652. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  75653. __decorate([
  75654. BABYLON.serializeAsMeshReference()
  75655. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  75656. __decorate([
  75657. BABYLON.serialize()
  75658. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  75659. __decorate([
  75660. BABYLON.serialize()
  75661. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  75662. __decorate([
  75663. BABYLON.serialize()
  75664. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  75665. __decorate([
  75666. BABYLON.serialize()
  75667. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  75668. __decorate([
  75669. BABYLON.serialize()
  75670. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  75671. return VolumetricLightScatteringPostProcess;
  75672. }(BABYLON.PostProcess));
  75673. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  75674. })(BABYLON || (BABYLON = {}));
  75675. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  75676. "use strict";
  75677. //
  75678. // This post-process allows the modification of rendered colors by using
  75679. // a 'look-up table' (LUT). This effect is also called Color Grading.
  75680. //
  75681. // The object needs to be provided an url to a texture containing the color
  75682. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  75683. // Use an image editing software to tweak the LUT to match your needs.
  75684. //
  75685. // For an example of a color LUT, see here:
  75686. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  75687. // For explanations on color grading, see here:
  75688. // http://udn.epicgames.com/Three/ColorGrading.html
  75689. //
  75690. var BABYLON;
  75691. (function (BABYLON) {
  75692. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  75693. __extends(ColorCorrectionPostProcess, _super);
  75694. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  75695. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  75696. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75697. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  75698. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75699. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75700. _this.onApply = function (effect) {
  75701. effect.setTexture("colorTable", _this._colorTableTexture);
  75702. };
  75703. return _this;
  75704. }
  75705. return ColorCorrectionPostProcess;
  75706. }(BABYLON.PostProcess));
  75707. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  75708. })(BABYLON || (BABYLON = {}));
  75709. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  75710. "use strict";
  75711. var BABYLON;
  75712. (function (BABYLON) {
  75713. var TonemappingOperator;
  75714. (function (TonemappingOperator) {
  75715. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  75716. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  75717. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  75718. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  75719. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  75720. ;
  75721. var TonemapPostProcess = /** @class */ (function (_super) {
  75722. __extends(TonemapPostProcess, _super);
  75723. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  75724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75725. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75726. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  75727. _this._operator = _operator;
  75728. _this.exposureAdjustment = exposureAdjustment;
  75729. var defines = "#define ";
  75730. if (_this._operator === TonemappingOperator.Hable)
  75731. defines += "HABLE_TONEMAPPING";
  75732. else if (_this._operator === TonemappingOperator.Reinhard)
  75733. defines += "REINHARD_TONEMAPPING";
  75734. else if (_this._operator === TonemappingOperator.HejiDawson)
  75735. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  75736. else if (_this._operator === TonemappingOperator.Photographic)
  75737. defines += "PHOTOGRAPHIC_TONEMAPPING";
  75738. //sadly a second call to create the effect.
  75739. _this.updateEffect(defines);
  75740. _this.onApply = function (effect) {
  75741. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  75742. };
  75743. return _this;
  75744. }
  75745. return TonemapPostProcess;
  75746. }(BABYLON.PostProcess));
  75747. BABYLON.TonemapPostProcess = TonemapPostProcess;
  75748. })(BABYLON || (BABYLON = {}));
  75749. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  75750. "use strict";
  75751. var BABYLON;
  75752. (function (BABYLON) {
  75753. var DisplayPassPostProcess = /** @class */ (function (_super) {
  75754. __extends(DisplayPassPostProcess, _super);
  75755. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  75756. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  75757. }
  75758. return DisplayPassPostProcess;
  75759. }(BABYLON.PostProcess));
  75760. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  75761. })(BABYLON || (BABYLON = {}));
  75762. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  75763. "use strict";
  75764. var BABYLON;
  75765. (function (BABYLON) {
  75766. var HighlightsPostProcess = /** @class */ (function (_super) {
  75767. __extends(HighlightsPostProcess, _super);
  75768. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75769. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75770. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75771. }
  75772. return HighlightsPostProcess;
  75773. }(BABYLON.PostProcess));
  75774. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  75775. })(BABYLON || (BABYLON = {}));
  75776. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  75777. "use strict";
  75778. var BABYLON;
  75779. (function (BABYLON) {
  75780. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  75781. __extends(ImageProcessingPostProcess, _super);
  75782. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  75783. if (camera === void 0) { camera = null; }
  75784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75785. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  75786. _this._fromLinearSpace = true;
  75787. /**
  75788. * Defines cache preventing GC.
  75789. */
  75790. _this._defines = {
  75791. IMAGEPROCESSING: false,
  75792. VIGNETTE: false,
  75793. VIGNETTEBLENDMODEMULTIPLY: false,
  75794. VIGNETTEBLENDMODEOPAQUE: false,
  75795. TONEMAPPING: false,
  75796. CONTRAST: false,
  75797. COLORCURVES: false,
  75798. COLORGRADING: false,
  75799. COLORGRADING3D: false,
  75800. FROMLINEARSPACE: false,
  75801. SAMPLER3DGREENDEPTH: false,
  75802. SAMPLER3DBGRMAP: false,
  75803. IMAGEPROCESSINGPOSTPROCESS: false,
  75804. EXPOSURE: false,
  75805. };
  75806. // Setup the configuration as forced by the constructor. This would then not force the
  75807. // scene materials output in linear space and let untouched the default forward pass.
  75808. if (imageProcessingConfiguration) {
  75809. imageProcessingConfiguration.applyByPostProcess = true;
  75810. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  75811. // This will cause the shader to be compiled
  75812. _this.fromLinearSpace = false;
  75813. }
  75814. else {
  75815. _this._attachImageProcessingConfiguration(null, true);
  75816. _this.imageProcessingConfiguration.applyByPostProcess = true;
  75817. }
  75818. _this.onApply = function (effect) {
  75819. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  75820. };
  75821. return _this;
  75822. }
  75823. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  75824. /**
  75825. * Gets the image processing configuration used either in this material.
  75826. */
  75827. get: function () {
  75828. return this._imageProcessingConfiguration;
  75829. },
  75830. /**
  75831. * Sets the Default image processing configuration used either in the this material.
  75832. *
  75833. * If sets to null, the scene one is in use.
  75834. */
  75835. set: function (value) {
  75836. this._attachImageProcessingConfiguration(value);
  75837. },
  75838. enumerable: true,
  75839. configurable: true
  75840. });
  75841. /**
  75842. * Attaches a new image processing configuration to the PBR Material.
  75843. * @param configuration
  75844. */
  75845. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  75846. var _this = this;
  75847. if (doNotBuild === void 0) { doNotBuild = false; }
  75848. if (configuration === this._imageProcessingConfiguration) {
  75849. return;
  75850. }
  75851. // Detaches observer.
  75852. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75853. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75854. }
  75855. // Pick the scene configuration if needed.
  75856. if (!configuration) {
  75857. var scene = null;
  75858. var engine = this.getEngine();
  75859. var camera = this.getCamera();
  75860. if (camera) {
  75861. scene = camera.getScene();
  75862. }
  75863. else if (engine && engine.scenes) {
  75864. var scenes = engine.scenes;
  75865. scene = scenes[scenes.length - 1];
  75866. }
  75867. else {
  75868. scene = BABYLON.Engine.LastCreatedScene;
  75869. }
  75870. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  75871. }
  75872. else {
  75873. this._imageProcessingConfiguration = configuration;
  75874. }
  75875. // Attaches observer.
  75876. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75877. _this._updateParameters();
  75878. });
  75879. // Ensure the effect will be rebuilt.
  75880. if (!doNotBuild) {
  75881. this._updateParameters();
  75882. }
  75883. };
  75884. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  75885. /**
  75886. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75887. */
  75888. get: function () {
  75889. return this.imageProcessingConfiguration.colorCurves;
  75890. },
  75891. /**
  75892. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75893. */
  75894. set: function (value) {
  75895. this.imageProcessingConfiguration.colorCurves = value;
  75896. },
  75897. enumerable: true,
  75898. configurable: true
  75899. });
  75900. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  75901. /**
  75902. * Gets wether the color curves effect is enabled.
  75903. */
  75904. get: function () {
  75905. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75906. },
  75907. /**
  75908. * Sets wether the color curves effect is enabled.
  75909. */
  75910. set: function (value) {
  75911. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75912. },
  75913. enumerable: true,
  75914. configurable: true
  75915. });
  75916. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  75917. /**
  75918. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75919. */
  75920. get: function () {
  75921. return this.imageProcessingConfiguration.colorGradingTexture;
  75922. },
  75923. /**
  75924. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75925. */
  75926. set: function (value) {
  75927. this.imageProcessingConfiguration.colorGradingTexture = value;
  75928. },
  75929. enumerable: true,
  75930. configurable: true
  75931. });
  75932. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  75933. /**
  75934. * Gets wether the color grading effect is enabled.
  75935. */
  75936. get: function () {
  75937. return this.imageProcessingConfiguration.colorGradingEnabled;
  75938. },
  75939. /**
  75940. * Gets wether the color grading effect is enabled.
  75941. */
  75942. set: function (value) {
  75943. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75944. },
  75945. enumerable: true,
  75946. configurable: true
  75947. });
  75948. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  75949. /**
  75950. * Gets exposure used in the effect.
  75951. */
  75952. get: function () {
  75953. return this.imageProcessingConfiguration.exposure;
  75954. },
  75955. /**
  75956. * Sets exposure used in the effect.
  75957. */
  75958. set: function (value) {
  75959. this.imageProcessingConfiguration.exposure = value;
  75960. },
  75961. enumerable: true,
  75962. configurable: true
  75963. });
  75964. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  75965. /**
  75966. * Gets wether tonemapping is enabled or not.
  75967. */
  75968. get: function () {
  75969. return this._imageProcessingConfiguration.toneMappingEnabled;
  75970. },
  75971. /**
  75972. * Sets wether tonemapping is enabled or not
  75973. */
  75974. set: function (value) {
  75975. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75976. },
  75977. enumerable: true,
  75978. configurable: true
  75979. });
  75980. ;
  75981. ;
  75982. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  75983. /**
  75984. * Gets contrast used in the effect.
  75985. */
  75986. get: function () {
  75987. return this.imageProcessingConfiguration.contrast;
  75988. },
  75989. /**
  75990. * Sets contrast used in the effect.
  75991. */
  75992. set: function (value) {
  75993. this.imageProcessingConfiguration.contrast = value;
  75994. },
  75995. enumerable: true,
  75996. configurable: true
  75997. });
  75998. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  75999. /**
  76000. * Gets Vignette stretch size.
  76001. */
  76002. get: function () {
  76003. return this.imageProcessingConfiguration.vignetteStretch;
  76004. },
  76005. /**
  76006. * Sets Vignette stretch size.
  76007. */
  76008. set: function (value) {
  76009. this.imageProcessingConfiguration.vignetteStretch = value;
  76010. },
  76011. enumerable: true,
  76012. configurable: true
  76013. });
  76014. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  76015. /**
  76016. * Gets Vignette centre X Offset.
  76017. */
  76018. get: function () {
  76019. return this.imageProcessingConfiguration.vignetteCentreX;
  76020. },
  76021. /**
  76022. * Sets Vignette centre X Offset.
  76023. */
  76024. set: function (value) {
  76025. this.imageProcessingConfiguration.vignetteCentreX = value;
  76026. },
  76027. enumerable: true,
  76028. configurable: true
  76029. });
  76030. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  76031. /**
  76032. * Gets Vignette centre Y Offset.
  76033. */
  76034. get: function () {
  76035. return this.imageProcessingConfiguration.vignetteCentreY;
  76036. },
  76037. /**
  76038. * Sets Vignette centre Y Offset.
  76039. */
  76040. set: function (value) {
  76041. this.imageProcessingConfiguration.vignetteCentreY = value;
  76042. },
  76043. enumerable: true,
  76044. configurable: true
  76045. });
  76046. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  76047. /**
  76048. * Gets Vignette weight or intensity of the vignette effect.
  76049. */
  76050. get: function () {
  76051. return this.imageProcessingConfiguration.vignetteWeight;
  76052. },
  76053. /**
  76054. * Sets Vignette weight or intensity of the vignette effect.
  76055. */
  76056. set: function (value) {
  76057. this.imageProcessingConfiguration.vignetteWeight = value;
  76058. },
  76059. enumerable: true,
  76060. configurable: true
  76061. });
  76062. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  76063. /**
  76064. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76065. * if vignetteEnabled is set to true.
  76066. */
  76067. get: function () {
  76068. return this.imageProcessingConfiguration.vignetteColor;
  76069. },
  76070. /**
  76071. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76072. * if vignetteEnabled is set to true.
  76073. */
  76074. set: function (value) {
  76075. this.imageProcessingConfiguration.vignetteColor = value;
  76076. },
  76077. enumerable: true,
  76078. configurable: true
  76079. });
  76080. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  76081. /**
  76082. * Gets Camera field of view used by the Vignette effect.
  76083. */
  76084. get: function () {
  76085. return this.imageProcessingConfiguration.vignetteCameraFov;
  76086. },
  76087. /**
  76088. * Sets Camera field of view used by the Vignette effect.
  76089. */
  76090. set: function (value) {
  76091. this.imageProcessingConfiguration.vignetteCameraFov = value;
  76092. },
  76093. enumerable: true,
  76094. configurable: true
  76095. });
  76096. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  76097. /**
  76098. * Gets the vignette blend mode allowing different kind of effect.
  76099. */
  76100. get: function () {
  76101. return this.imageProcessingConfiguration.vignetteBlendMode;
  76102. },
  76103. /**
  76104. * Sets the vignette blend mode allowing different kind of effect.
  76105. */
  76106. set: function (value) {
  76107. this.imageProcessingConfiguration.vignetteBlendMode = value;
  76108. },
  76109. enumerable: true,
  76110. configurable: true
  76111. });
  76112. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  76113. /**
  76114. * Gets wether the vignette effect is enabled.
  76115. */
  76116. get: function () {
  76117. return this.imageProcessingConfiguration.vignetteEnabled;
  76118. },
  76119. /**
  76120. * Sets wether the vignette effect is enabled.
  76121. */
  76122. set: function (value) {
  76123. this.imageProcessingConfiguration.vignetteEnabled = value;
  76124. },
  76125. enumerable: true,
  76126. configurable: true
  76127. });
  76128. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  76129. /**
  76130. * Gets wether the input of the processing is in Gamma or Linear Space.
  76131. */
  76132. get: function () {
  76133. return this._fromLinearSpace;
  76134. },
  76135. /**
  76136. * Sets wether the input of the processing is in Gamma or Linear Space.
  76137. */
  76138. set: function (value) {
  76139. if (this._fromLinearSpace === value) {
  76140. return;
  76141. }
  76142. this._fromLinearSpace = value;
  76143. this._updateParameters();
  76144. },
  76145. enumerable: true,
  76146. configurable: true
  76147. });
  76148. ImageProcessingPostProcess.prototype.getClassName = function () {
  76149. return "ImageProcessingPostProcess";
  76150. };
  76151. ImageProcessingPostProcess.prototype._updateParameters = function () {
  76152. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  76153. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  76154. var defines = "";
  76155. for (var define in this._defines) {
  76156. if (this._defines[define]) {
  76157. defines += "#define " + define + ";\r\n";
  76158. }
  76159. }
  76160. var samplers = ["textureSampler"];
  76161. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  76162. var uniforms = ["scale"];
  76163. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  76164. this.updateEffect(defines, uniforms, samplers);
  76165. };
  76166. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  76167. _super.prototype.dispose.call(this, camera);
  76168. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76169. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76170. }
  76171. this.imageProcessingConfiguration.applyByPostProcess = false;
  76172. };
  76173. __decorate([
  76174. BABYLON.serialize()
  76175. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  76176. return ImageProcessingPostProcess;
  76177. }(BABYLON.PostProcess));
  76178. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  76179. })(BABYLON || (BABYLON = {}));
  76180. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  76181. "use strict";
  76182. var BABYLON;
  76183. (function (BABYLON) {
  76184. var Bone = /** @class */ (function (_super) {
  76185. __extends(Bone, _super);
  76186. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76187. if (parentBone === void 0) { parentBone = null; }
  76188. if (localMatrix === void 0) { localMatrix = null; }
  76189. if (restPose === void 0) { restPose = null; }
  76190. if (baseMatrix === void 0) { baseMatrix = null; }
  76191. if (index === void 0) { index = null; }
  76192. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76193. _this.name = name;
  76194. _this.children = new Array();
  76195. _this.animations = new Array();
  76196. // Set this value to map this bone to a different index in the transform matrices.
  76197. // Set this value to -1 to exclude the bone from the transform matrices.
  76198. _this._index = null;
  76199. _this._worldTransform = new BABYLON.Matrix();
  76200. _this._absoluteTransform = new BABYLON.Matrix();
  76201. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76202. _this._scaleMatrix = BABYLON.Matrix.Identity();
  76203. _this._scaleVector = BABYLON.Vector3.One();
  76204. _this._negateScaleChildren = BABYLON.Vector3.One();
  76205. _this._scalingDeterminant = 1;
  76206. _this._skeleton = skeleton;
  76207. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  76208. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76209. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76210. _this._index = index;
  76211. skeleton.bones.push(_this);
  76212. _this.setParent(parentBone, false);
  76213. _this._updateDifferenceMatrix();
  76214. return _this;
  76215. }
  76216. Object.defineProperty(Bone.prototype, "_matrix", {
  76217. get: function () {
  76218. return this._localMatrix;
  76219. },
  76220. set: function (value) {
  76221. this._localMatrix.copyFrom(value);
  76222. },
  76223. enumerable: true,
  76224. configurable: true
  76225. });
  76226. // Members
  76227. Bone.prototype.getSkeleton = function () {
  76228. return this._skeleton;
  76229. };
  76230. Bone.prototype.getParent = function () {
  76231. return this._parent;
  76232. };
  76233. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76234. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76235. if (this._parent === parent) {
  76236. return;
  76237. }
  76238. if (this._parent) {
  76239. var index = this._parent.children.indexOf(this);
  76240. if (index !== -1) {
  76241. this._parent.children.splice(index, 1);
  76242. }
  76243. }
  76244. this._parent = parent;
  76245. if (this._parent) {
  76246. this._parent.children.push(this);
  76247. }
  76248. if (updateDifferenceMatrix) {
  76249. this._updateDifferenceMatrix();
  76250. }
  76251. this.markAsDirty();
  76252. };
  76253. Bone.prototype.getLocalMatrix = function () {
  76254. return this._localMatrix;
  76255. };
  76256. Bone.prototype.getBaseMatrix = function () {
  76257. return this._baseMatrix;
  76258. };
  76259. Bone.prototype.getRestPose = function () {
  76260. return this._restPose;
  76261. };
  76262. Bone.prototype.returnToRest = function () {
  76263. this.updateMatrix(this._restPose.clone());
  76264. };
  76265. Bone.prototype.getWorldMatrix = function () {
  76266. return this._worldTransform;
  76267. };
  76268. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76269. return this._invertedAbsoluteTransform;
  76270. };
  76271. Bone.prototype.getAbsoluteTransform = function () {
  76272. return this._absoluteTransform;
  76273. };
  76274. Object.defineProperty(Bone.prototype, "position", {
  76275. // Properties (matches AbstractMesh properties)
  76276. get: function () {
  76277. return this.getPosition();
  76278. },
  76279. set: function (newPosition) {
  76280. this.setPosition(newPosition);
  76281. },
  76282. enumerable: true,
  76283. configurable: true
  76284. });
  76285. Object.defineProperty(Bone.prototype, "rotation", {
  76286. get: function () {
  76287. return this.getRotation();
  76288. },
  76289. set: function (newRotation) {
  76290. this.setRotation(newRotation);
  76291. },
  76292. enumerable: true,
  76293. configurable: true
  76294. });
  76295. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76296. get: function () {
  76297. return this.getRotationQuaternion();
  76298. },
  76299. set: function (newRotation) {
  76300. this.setRotationQuaternion(newRotation);
  76301. },
  76302. enumerable: true,
  76303. configurable: true
  76304. });
  76305. Object.defineProperty(Bone.prototype, "scaling", {
  76306. get: function () {
  76307. var value = BABYLON.Vector3.One();
  76308. this._localMatrix.decompose(value, undefined, undefined);
  76309. return value;
  76310. },
  76311. set: function (newScaling) {
  76312. this._localMatrix.decompose(undefined, Bone._tmpQuat, Bone._tmpVecs[0]);
  76313. BABYLON.Matrix.ComposeToRef(newScaling, Bone._tmpQuat, Bone._tmpVecs[0], this._localMatrix);
  76314. this.markAsDirty();
  76315. },
  76316. enumerable: true,
  76317. configurable: true
  76318. });
  76319. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76320. /**
  76321. * Gets the animation properties override
  76322. */
  76323. get: function () {
  76324. return this._skeleton.animationPropertiesOverride;
  76325. },
  76326. enumerable: true,
  76327. configurable: true
  76328. });
  76329. // Methods
  76330. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  76331. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76332. this._baseMatrix.copyFrom(matrix);
  76333. this._localMatrix.copyFrom(matrix);
  76334. if (updateDifferenceMatrix) {
  76335. this._updateDifferenceMatrix();
  76336. }
  76337. this.markAsDirty();
  76338. };
  76339. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  76340. if (!rootMatrix) {
  76341. rootMatrix = this._baseMatrix;
  76342. }
  76343. if (this._parent) {
  76344. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76345. }
  76346. else {
  76347. this._absoluteTransform.copyFrom(rootMatrix);
  76348. }
  76349. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76350. for (var index = 0; index < this.children.length; index++) {
  76351. this.children[index]._updateDifferenceMatrix();
  76352. }
  76353. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76354. };
  76355. Bone.prototype.markAsDirty = function () {
  76356. this._currentRenderId++;
  76357. this._childRenderId++;
  76358. this._skeleton._markAsDirty();
  76359. };
  76360. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76361. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76362. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76363. // all animation may be coming from a library skeleton, so may need to create animation
  76364. if (this.animations.length === 0) {
  76365. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  76366. this.animations[0].setKeys([]);
  76367. }
  76368. // get animation info / verify there is such a range from the source bone
  76369. var sourceRange = source.animations[0].getRange(rangeName);
  76370. if (!sourceRange) {
  76371. return false;
  76372. }
  76373. var from = sourceRange.from;
  76374. var to = sourceRange.to;
  76375. var sourceKeys = source.animations[0].getKeys();
  76376. // rescaling prep
  76377. var sourceBoneLength = source.length;
  76378. var sourceParent = source.getParent();
  76379. var parent = this.getParent();
  76380. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  76381. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  76382. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  76383. var destKeys = this.animations[0].getKeys();
  76384. // loop vars declaration
  76385. var orig;
  76386. var origTranslation;
  76387. var mat;
  76388. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  76389. orig = sourceKeys[key];
  76390. if (orig.frame >= from && orig.frame <= to) {
  76391. if (rescaleAsRequired) {
  76392. mat = orig.value.clone();
  76393. // scale based on parent ratio, when bone has parent
  76394. if (parentScalingReqd) {
  76395. origTranslation = mat.getTranslation();
  76396. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  76397. // scale based on skeleton dimension ratio when root bone, and value is passed
  76398. }
  76399. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  76400. origTranslation = mat.getTranslation();
  76401. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  76402. // use original when root bone, and no data for skelDimensionsRatio
  76403. }
  76404. else {
  76405. mat = orig.value;
  76406. }
  76407. }
  76408. else {
  76409. mat = orig.value;
  76410. }
  76411. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  76412. }
  76413. }
  76414. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  76415. return true;
  76416. };
  76417. /**
  76418. * Translate the bone in local or world space.
  76419. * @param vec The amount to translate the bone.
  76420. * @param space The space that the translation is in.
  76421. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76422. */
  76423. Bone.prototype.translate = function (vec, space, mesh) {
  76424. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76425. var lm = this.getLocalMatrix();
  76426. if (space == BABYLON.Space.LOCAL) {
  76427. lm.m[12] += vec.x;
  76428. lm.m[13] += vec.y;
  76429. lm.m[14] += vec.z;
  76430. }
  76431. else {
  76432. var wm = null;
  76433. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76434. if (mesh) {
  76435. wm = mesh.getWorldMatrix();
  76436. }
  76437. this._skeleton.computeAbsoluteTransforms();
  76438. var tmat = Bone._tmpMats[0];
  76439. var tvec = Bone._tmpVecs[0];
  76440. if (this._parent) {
  76441. if (mesh && wm) {
  76442. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76443. tmat.multiplyToRef(wm, tmat);
  76444. }
  76445. else {
  76446. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76447. }
  76448. }
  76449. tmat.m[12] = 0;
  76450. tmat.m[13] = 0;
  76451. tmat.m[14] = 0;
  76452. tmat.invert();
  76453. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  76454. lm.m[12] += tvec.x;
  76455. lm.m[13] += tvec.y;
  76456. lm.m[14] += tvec.z;
  76457. }
  76458. this.markAsDirty();
  76459. };
  76460. /**
  76461. * Set the postion of the bone in local or world space.
  76462. * @param position The position to set the bone.
  76463. * @param space The space that the position is in.
  76464. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76465. */
  76466. Bone.prototype.setPosition = function (position, space, mesh) {
  76467. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76468. var lm = this.getLocalMatrix();
  76469. if (space == BABYLON.Space.LOCAL) {
  76470. lm.m[12] = position.x;
  76471. lm.m[13] = position.y;
  76472. lm.m[14] = position.z;
  76473. }
  76474. else {
  76475. var wm = null;
  76476. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76477. if (mesh) {
  76478. wm = mesh.getWorldMatrix();
  76479. }
  76480. this._skeleton.computeAbsoluteTransforms();
  76481. var tmat = Bone._tmpMats[0];
  76482. var vec = Bone._tmpVecs[0];
  76483. if (this._parent) {
  76484. if (mesh && wm) {
  76485. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76486. tmat.multiplyToRef(wm, tmat);
  76487. }
  76488. else {
  76489. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76490. }
  76491. }
  76492. tmat.invert();
  76493. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  76494. lm.m[12] = vec.x;
  76495. lm.m[13] = vec.y;
  76496. lm.m[14] = vec.z;
  76497. }
  76498. this.markAsDirty();
  76499. };
  76500. /**
  76501. * Set the absolute postion of the bone (world space).
  76502. * @param position The position to set the bone.
  76503. * @param mesh The mesh that this bone is attached to.
  76504. */
  76505. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  76506. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  76507. };
  76508. /**
  76509. * Adds an additional scale to the bone on the x, y and z axes.
  76510. * @param x The additional scale of the bone on the x axis.
  76511. * @param y The additional scale of the bone on the y axis.
  76512. * @param z The additional scale of the bone on the z axis.
  76513. * @param scaleChildren Set this to true if children of the bone should be scaled.
  76514. */
  76515. Bone.prototype.setAdditionalScale = function (x, y, z, scaleChildren) {
  76516. if (scaleChildren === void 0) { scaleChildren = false; }
  76517. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  76518. if (!scaleChildren) {
  76519. this._negateScaleChildren.x = 1 / x;
  76520. this._negateScaleChildren.y = 1 / y;
  76521. this._negateScaleChildren.z = 1 / z;
  76522. }
  76523. this._syncScaleVector();
  76524. }
  76525. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  76526. };
  76527. /**
  76528. * Scale the bone on the x, y and z axes.
  76529. * @param x The amount to scale the bone on the x axis.
  76530. * @param x The amount to scale the bone on the y axis.
  76531. * @param z The amount to scale the bone on the z axis.
  76532. * @param scaleChildren Set this to true if children of the bone should be scaled.
  76533. */
  76534. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  76535. if (scaleChildren === void 0) { scaleChildren = false; }
  76536. var locMat = this.getLocalMatrix();
  76537. var origLocMat = Bone._tmpMats[0];
  76538. origLocMat.copyFrom(locMat);
  76539. var origLocMatInv = Bone._tmpMats[1];
  76540. origLocMatInv.copyFrom(origLocMat);
  76541. origLocMatInv.invert();
  76542. var scaleMat = Bone._tmpMats[2];
  76543. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  76544. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  76545. this._scaleVector.x *= x;
  76546. this._scaleVector.y *= y;
  76547. this._scaleVector.z *= z;
  76548. locMat.multiplyToRef(origLocMatInv, locMat);
  76549. locMat.multiplyToRef(scaleMat, locMat);
  76550. locMat.multiplyToRef(origLocMat, locMat);
  76551. var parent = this.getParent();
  76552. if (parent) {
  76553. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  76554. }
  76555. else {
  76556. this.getAbsoluteTransform().copyFrom(locMat);
  76557. }
  76558. var len = this.children.length;
  76559. scaleMat.invert();
  76560. for (var i = 0; i < len; i++) {
  76561. var child = this.children[i];
  76562. var cm = child.getLocalMatrix();
  76563. cm.multiplyToRef(scaleMat, cm);
  76564. var lm = child.getLocalMatrix();
  76565. lm.m[12] *= x;
  76566. lm.m[13] *= y;
  76567. lm.m[14] *= z;
  76568. }
  76569. this.computeAbsoluteTransforms();
  76570. if (scaleChildren) {
  76571. for (var i = 0; i < len; i++) {
  76572. this.children[i].scale(x, y, z, scaleChildren);
  76573. }
  76574. }
  76575. this.markAsDirty();
  76576. };
  76577. /**
  76578. * Set the yaw, pitch, and roll of the bone in local or world space.
  76579. * @param yaw The rotation of the bone on the y axis.
  76580. * @param pitch The rotation of the bone on the x axis.
  76581. * @param roll The rotation of the bone on the z axis.
  76582. * @param space The space that the axes of rotation are in.
  76583. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76584. */
  76585. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  76586. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76587. var rotMatInv = Bone._tmpMats[0];
  76588. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76589. return;
  76590. }
  76591. var rotMat = Bone._tmpMats[1];
  76592. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  76593. rotMatInv.multiplyToRef(rotMat, rotMat);
  76594. this._rotateWithMatrix(rotMat, space, mesh);
  76595. };
  76596. /**
  76597. * Rotate the bone on an axis in local or world space.
  76598. * @param axis The axis to rotate the bone on.
  76599. * @param amount The amount to rotate the bone.
  76600. * @param space The space that the axis is in.
  76601. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76602. */
  76603. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  76604. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76605. var rmat = Bone._tmpMats[0];
  76606. rmat.m[12] = 0;
  76607. rmat.m[13] = 0;
  76608. rmat.m[14] = 0;
  76609. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  76610. this._rotateWithMatrix(rmat, space, mesh);
  76611. };
  76612. /**
  76613. * Set the rotation of the bone to a particular axis angle in local or world space.
  76614. * @param axis The axis to rotate the bone on.
  76615. * @param angle The angle that the bone should be rotated to.
  76616. * @param space The space that the axis is in.
  76617. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76618. */
  76619. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  76620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76621. var rotMatInv = Bone._tmpMats[0];
  76622. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76623. return;
  76624. }
  76625. var rotMat = Bone._tmpMats[1];
  76626. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  76627. rotMatInv.multiplyToRef(rotMat, rotMat);
  76628. this._rotateWithMatrix(rotMat, space, mesh);
  76629. };
  76630. /**
  76631. * Set the euler rotation of the bone in local of world space.
  76632. * @param rotation The euler rotation that the bone should be set to.
  76633. * @param space The space that the rotation is in.
  76634. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76635. */
  76636. Bone.prototype.setRotation = function (rotation, space, mesh) {
  76637. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76638. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  76639. };
  76640. /**
  76641. * Set the quaternion rotation of the bone in local of world space.
  76642. * @param quat The quaternion rotation that the bone should be set to.
  76643. * @param space The space that the rotation is in.
  76644. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76645. */
  76646. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  76647. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76648. var rotMatInv = Bone._tmpMats[0];
  76649. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76650. return;
  76651. }
  76652. var rotMat = Bone._tmpMats[1];
  76653. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  76654. rotMatInv.multiplyToRef(rotMat, rotMat);
  76655. this._rotateWithMatrix(rotMat, space, mesh);
  76656. };
  76657. /**
  76658. * Set the rotation matrix of the bone in local of world space.
  76659. * @param rotMat The rotation matrix that the bone should be set to.
  76660. * @param space The space that the rotation is in.
  76661. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76662. */
  76663. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  76664. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76665. var rotMatInv = Bone._tmpMats[0];
  76666. if (!this._getNegativeRotationToRef(rotMatInv, space, mesh)) {
  76667. return;
  76668. }
  76669. var rotMat2 = Bone._tmpMats[1];
  76670. rotMat2.copyFrom(rotMat);
  76671. rotMatInv.multiplyToRef(rotMat, rotMat2);
  76672. this._rotateWithMatrix(rotMat2, space, mesh);
  76673. };
  76674. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  76675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76676. var lmat = this.getLocalMatrix();
  76677. var lx = lmat.m[12];
  76678. var ly = lmat.m[13];
  76679. var lz = lmat.m[14];
  76680. var parent = this.getParent();
  76681. var parentScale = Bone._tmpMats[3];
  76682. var parentScaleInv = Bone._tmpMats[4];
  76683. if (parent) {
  76684. if (space == BABYLON.Space.WORLD) {
  76685. if (mesh) {
  76686. parentScale.copyFrom(mesh.getWorldMatrix());
  76687. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  76688. }
  76689. else {
  76690. parentScale.copyFrom(parent.getAbsoluteTransform());
  76691. }
  76692. }
  76693. else {
  76694. parentScale = parent._scaleMatrix;
  76695. }
  76696. parentScaleInv.copyFrom(parentScale);
  76697. parentScaleInv.invert();
  76698. lmat.multiplyToRef(parentScale, lmat);
  76699. lmat.multiplyToRef(rmat, lmat);
  76700. lmat.multiplyToRef(parentScaleInv, lmat);
  76701. }
  76702. else {
  76703. if (space == BABYLON.Space.WORLD && mesh) {
  76704. parentScale.copyFrom(mesh.getWorldMatrix());
  76705. parentScaleInv.copyFrom(parentScale);
  76706. parentScaleInv.invert();
  76707. lmat.multiplyToRef(parentScale, lmat);
  76708. lmat.multiplyToRef(rmat, lmat);
  76709. lmat.multiplyToRef(parentScaleInv, lmat);
  76710. }
  76711. else {
  76712. lmat.multiplyToRef(rmat, lmat);
  76713. }
  76714. }
  76715. lmat.m[12] = lx;
  76716. lmat.m[13] = ly;
  76717. lmat.m[14] = lz;
  76718. this.computeAbsoluteTransforms();
  76719. this.markAsDirty();
  76720. };
  76721. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  76722. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76723. if (space == BABYLON.Space.WORLD) {
  76724. var scaleMatrix = Bone._tmpMats[2];
  76725. scaleMatrix.copyFrom(this._scaleMatrix);
  76726. rotMatInv.copyFrom(this.getAbsoluteTransform());
  76727. if (mesh) {
  76728. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  76729. var meshScale = Bone._tmpMats[3];
  76730. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  76731. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  76732. }
  76733. rotMatInv.invert();
  76734. if (isNaN(rotMatInv.m[0])) {
  76735. // Matrix failed to invert.
  76736. // This can happen if scale is zero for example.
  76737. return false;
  76738. }
  76739. scaleMatrix.m[0] *= this._scalingDeterminant;
  76740. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76741. }
  76742. else {
  76743. rotMatInv.copyFrom(this.getLocalMatrix());
  76744. rotMatInv.invert();
  76745. if (isNaN(rotMatInv.m[0])) {
  76746. // Matrix failed to invert.
  76747. // This can happen if scale is zero for example.
  76748. return false;
  76749. }
  76750. var scaleMatrix = Bone._tmpMats[2];
  76751. scaleMatrix.copyFrom(this._scaleMatrix);
  76752. if (this._parent) {
  76753. var pscaleMatrix = Bone._tmpMats[3];
  76754. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  76755. pscaleMatrix.invert();
  76756. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  76757. }
  76758. else {
  76759. scaleMatrix.m[0] *= this._scalingDeterminant;
  76760. }
  76761. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76762. }
  76763. return true;
  76764. };
  76765. /**
  76766. * Get the additional scale of the bone
  76767. * @returns the additional scale of the bone
  76768. */
  76769. Bone.prototype.getAdditionalScale = function () {
  76770. return this._scaleVector.clone();
  76771. };
  76772. /**
  76773. * Copy the additional scale of the bone to a vector3.
  76774. * @param result The vector3 to copy the additional scale to
  76775. */
  76776. Bone.prototype.getAdditionalScaleToRef = function (result) {
  76777. result.copyFrom(this._scaleVector);
  76778. };
  76779. /**
  76780. * Get the position of the bone in local or world space.
  76781. * @param space The space that the returned position is in.
  76782. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76783. * @returns The position of the bone
  76784. */
  76785. Bone.prototype.getPosition = function (space, mesh) {
  76786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76787. if (mesh === void 0) { mesh = null; }
  76788. var pos = BABYLON.Vector3.Zero();
  76789. this.getPositionToRef(space, mesh, pos);
  76790. return pos;
  76791. };
  76792. /**
  76793. * Copy the position of the bone to a vector3 in local or world space.
  76794. * @param space The space that the returned position is in.
  76795. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76796. * @param result The vector3 to copy the position to.
  76797. */
  76798. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  76799. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76800. if (space == BABYLON.Space.LOCAL) {
  76801. var lm = this.getLocalMatrix();
  76802. result.x = lm.m[12];
  76803. result.y = lm.m[13];
  76804. result.z = lm.m[14];
  76805. }
  76806. else {
  76807. var wm = null;
  76808. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76809. if (mesh) {
  76810. wm = mesh.getWorldMatrix();
  76811. }
  76812. this._skeleton.computeAbsoluteTransforms();
  76813. var tmat = Bone._tmpMats[0];
  76814. if (mesh && wm) {
  76815. tmat.copyFrom(this.getAbsoluteTransform());
  76816. tmat.multiplyToRef(wm, tmat);
  76817. }
  76818. else {
  76819. tmat = this.getAbsoluteTransform();
  76820. }
  76821. result.x = tmat.m[12];
  76822. result.y = tmat.m[13];
  76823. result.z = tmat.m[14];
  76824. }
  76825. };
  76826. /**
  76827. * Get the absolute position of the bone (world space).
  76828. * @param mesh The mesh that this bone is attached to.
  76829. * @returns The absolute position of the bone
  76830. */
  76831. Bone.prototype.getAbsolutePosition = function (mesh) {
  76832. if (mesh === void 0) { mesh = null; }
  76833. var pos = BABYLON.Vector3.Zero();
  76834. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  76835. return pos;
  76836. };
  76837. /**
  76838. * Copy the absolute position of the bone (world space) to the result param.
  76839. * @param mesh The mesh that this bone is attached to.
  76840. * @param result The vector3 to copy the absolute position to.
  76841. */
  76842. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  76843. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  76844. };
  76845. /**
  76846. * Compute the absolute transforms of this bone and its children.
  76847. */
  76848. Bone.prototype.computeAbsoluteTransforms = function () {
  76849. if (this._parent) {
  76850. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76851. }
  76852. else {
  76853. this._absoluteTransform.copyFrom(this._localMatrix);
  76854. var poseMatrix = this._skeleton.getPoseMatrix();
  76855. if (poseMatrix) {
  76856. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  76857. }
  76858. }
  76859. var children = this.children;
  76860. var len = children.length;
  76861. for (var i = 0; i < len; i++) {
  76862. children[i].computeAbsoluteTransforms();
  76863. }
  76864. };
  76865. Bone.prototype._syncScaleVector = function () {
  76866. var lm = this.getLocalMatrix();
  76867. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  76868. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  76869. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  76870. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  76871. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  76872. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  76873. this._scaleVector.x = xs * Math.sqrt(xsq);
  76874. this._scaleVector.y = ys * Math.sqrt(ysq);
  76875. this._scaleVector.z = zs * Math.sqrt(zsq);
  76876. if (this._parent) {
  76877. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  76878. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  76879. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  76880. }
  76881. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  76882. };
  76883. /**
  76884. * Get the world direction from an axis that is in the local space of the bone.
  76885. * @param localAxis The local direction that is used to compute the world direction.
  76886. * @param mesh The mesh that this bone is attached to.
  76887. * @returns The world direction
  76888. */
  76889. Bone.prototype.getDirection = function (localAxis, mesh) {
  76890. if (mesh === void 0) { mesh = null; }
  76891. var result = BABYLON.Vector3.Zero();
  76892. this.getDirectionToRef(localAxis, mesh, result);
  76893. return result;
  76894. };
  76895. /**
  76896. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  76897. * @param localAxis The local direction that is used to compute the world direction.
  76898. * @param mesh The mesh that this bone is attached to.
  76899. * @param result The vector3 that the world direction will be copied to.
  76900. */
  76901. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  76902. if (mesh === void 0) { mesh = null; }
  76903. var wm = null;
  76904. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76905. if (mesh) {
  76906. wm = mesh.getWorldMatrix();
  76907. }
  76908. this._skeleton.computeAbsoluteTransforms();
  76909. var mat = Bone._tmpMats[0];
  76910. mat.copyFrom(this.getAbsoluteTransform());
  76911. if (mesh && wm) {
  76912. mat.multiplyToRef(wm, mat);
  76913. }
  76914. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  76915. result.normalize();
  76916. };
  76917. /**
  76918. * Get the euler rotation of the bone in local or world space.
  76919. * @param space The space that the rotation should be in.
  76920. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76921. * @returns The euler rotation
  76922. */
  76923. Bone.prototype.getRotation = function (space, mesh) {
  76924. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76925. if (mesh === void 0) { mesh = null; }
  76926. var result = BABYLON.Vector3.Zero();
  76927. this.getRotationToRef(space, mesh, result);
  76928. return result;
  76929. };
  76930. /**
  76931. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  76932. * @param space The space that the rotation should be in.
  76933. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76934. * @param result The vector3 that the rotation should be copied to.
  76935. */
  76936. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  76937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76938. if (mesh === void 0) { mesh = null; }
  76939. var quat = Bone._tmpQuat;
  76940. this.getRotationQuaternionToRef(space, mesh, quat);
  76941. quat.toEulerAnglesToRef(result);
  76942. };
  76943. /**
  76944. * Get the quaternion rotation of the bone in either local or world space.
  76945. * @param space The space that the rotation should be in.
  76946. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76947. * @returns The quaternion rotation
  76948. */
  76949. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  76950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76951. if (mesh === void 0) { mesh = null; }
  76952. var result = BABYLON.Quaternion.Identity();
  76953. this.getRotationQuaternionToRef(space, mesh, result);
  76954. return result;
  76955. };
  76956. /**
  76957. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  76958. * @param space The space that the rotation should be in.
  76959. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76960. * @param result The quaternion that the rotation should be copied to.
  76961. */
  76962. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  76963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76964. if (mesh === void 0) { mesh = null; }
  76965. if (space == BABYLON.Space.LOCAL) {
  76966. this.getLocalMatrix().decompose(undefined, result, undefined);
  76967. }
  76968. else {
  76969. var mat = Bone._tmpMats[0];
  76970. var amat = this.getAbsoluteTransform();
  76971. if (mesh) {
  76972. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76973. }
  76974. else {
  76975. mat.copyFrom(amat);
  76976. }
  76977. mat.m[0] *= this._scalingDeterminant;
  76978. mat.m[1] *= this._scalingDeterminant;
  76979. mat.m[2] *= this._scalingDeterminant;
  76980. mat.decompose(undefined, result, undefined);
  76981. }
  76982. };
  76983. /**
  76984. * Get the rotation matrix of the bone in local or world space.
  76985. * @param space The space that the rotation should be in.
  76986. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76987. * @returns The rotation matrix
  76988. */
  76989. Bone.prototype.getRotationMatrix = function (space, mesh) {
  76990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76991. var result = BABYLON.Matrix.Identity();
  76992. this.getRotationMatrixToRef(space, mesh, result);
  76993. return result;
  76994. };
  76995. /**
  76996. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  76997. * @param space The space that the rotation should be in.
  76998. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76999. * @param result The quaternion that the rotation should be copied to.
  77000. */
  77001. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  77002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77003. if (space == BABYLON.Space.LOCAL) {
  77004. this.getLocalMatrix().getRotationMatrixToRef(result);
  77005. }
  77006. else {
  77007. var mat = Bone._tmpMats[0];
  77008. var amat = this.getAbsoluteTransform();
  77009. if (mesh) {
  77010. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77011. }
  77012. else {
  77013. mat.copyFrom(amat);
  77014. }
  77015. mat.m[0] *= this._scalingDeterminant;
  77016. mat.m[1] *= this._scalingDeterminant;
  77017. mat.m[2] *= this._scalingDeterminant;
  77018. mat.getRotationMatrixToRef(result);
  77019. }
  77020. };
  77021. /**
  77022. * Get the world position of a point that is in the local space of the bone.
  77023. * @param position The local position
  77024. * @param mesh The mesh that this bone is attached to.
  77025. * @returns The world position
  77026. */
  77027. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  77028. if (mesh === void 0) { mesh = null; }
  77029. var result = BABYLON.Vector3.Zero();
  77030. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  77031. return result;
  77032. };
  77033. /**
  77034. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  77035. * @param position The local position
  77036. * @param mesh The mesh that this bone is attached to.
  77037. * @param result The vector3 that the world position should be copied to.
  77038. */
  77039. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  77040. if (mesh === void 0) { mesh = null; }
  77041. var wm = null;
  77042. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77043. if (mesh) {
  77044. wm = mesh.getWorldMatrix();
  77045. }
  77046. this._skeleton.computeAbsoluteTransforms();
  77047. var tmat = Bone._tmpMats[0];
  77048. if (mesh && wm) {
  77049. tmat.copyFrom(this.getAbsoluteTransform());
  77050. tmat.multiplyToRef(wm, tmat);
  77051. }
  77052. else {
  77053. tmat = this.getAbsoluteTransform();
  77054. }
  77055. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77056. };
  77057. /**
  77058. * Get the local position of a point that is in world space.
  77059. * @param position The world position
  77060. * @param mesh The mesh that this bone is attached to.
  77061. * @returns The local position
  77062. */
  77063. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  77064. if (mesh === void 0) { mesh = null; }
  77065. var result = BABYLON.Vector3.Zero();
  77066. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  77067. return result;
  77068. };
  77069. /**
  77070. * Get the local position of a point that is in world space and copy it to the result param.
  77071. * @param position The world position
  77072. * @param mesh The mesh that this bone is attached to.
  77073. * @param result The vector3 that the local position should be copied to.
  77074. */
  77075. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  77076. if (mesh === void 0) { mesh = null; }
  77077. var wm = null;
  77078. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77079. if (mesh) {
  77080. wm = mesh.getWorldMatrix();
  77081. }
  77082. this._skeleton.computeAbsoluteTransforms();
  77083. var tmat = Bone._tmpMats[0];
  77084. tmat.copyFrom(this.getAbsoluteTransform());
  77085. if (mesh && wm) {
  77086. tmat.multiplyToRef(wm, tmat);
  77087. }
  77088. tmat.invert();
  77089. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77090. };
  77091. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77092. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  77093. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77094. return Bone;
  77095. }(BABYLON.Node));
  77096. BABYLON.Bone = Bone;
  77097. })(BABYLON || (BABYLON = {}));
  77098. //# sourceMappingURL=babylon.bone.js.map
  77099. "use strict";
  77100. var BABYLON;
  77101. (function (BABYLON) {
  77102. var BoneIKController = /** @class */ (function () {
  77103. function BoneIKController(mesh, bone, options) {
  77104. this.targetPosition = BABYLON.Vector3.Zero();
  77105. this.poleTargetPosition = BABYLON.Vector3.Zero();
  77106. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  77107. this.poleAngle = 0;
  77108. this.slerpAmount = 1;
  77109. this._bone1Quat = BABYLON.Quaternion.Identity();
  77110. this._bone1Mat = BABYLON.Matrix.Identity();
  77111. this._bone2Ang = Math.PI;
  77112. this._maxAngle = Math.PI;
  77113. this._rightHandedSystem = false;
  77114. this._bendAxis = BABYLON.Vector3.Right();
  77115. this._slerping = false;
  77116. this._adjustRoll = 0;
  77117. this._bone2 = bone;
  77118. this._bone1 = bone.getParent();
  77119. if (!this._bone1) {
  77120. return;
  77121. }
  77122. this.mesh = mesh;
  77123. var bonePos = bone.getPosition();
  77124. if (bone.getAbsoluteTransform().determinant() > 0) {
  77125. this._rightHandedSystem = true;
  77126. this._bendAxis.x = 0;
  77127. this._bendAxis.y = 0;
  77128. this._bendAxis.z = -1;
  77129. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  77130. this._adjustRoll = Math.PI * .5;
  77131. this._bendAxis.z = 1;
  77132. }
  77133. }
  77134. if (this._bone1.length) {
  77135. var boneScale1 = this._bone1.getAdditionalScale();
  77136. var boneScale2 = this._bone2.getAdditionalScale();
  77137. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  77138. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  77139. }
  77140. else if (this._bone1.children[0]) {
  77141. mesh.computeWorldMatrix(true);
  77142. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  77143. var pos2 = this._bone2.getAbsolutePosition(mesh);
  77144. var pos3 = this._bone1.getAbsolutePosition(mesh);
  77145. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  77146. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  77147. }
  77148. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  77149. this.maxAngle = Math.PI;
  77150. if (options) {
  77151. if (options.targetMesh) {
  77152. this.targetMesh = options.targetMesh;
  77153. this.targetMesh.computeWorldMatrix(true);
  77154. }
  77155. if (options.poleTargetMesh) {
  77156. this.poleTargetMesh = options.poleTargetMesh;
  77157. this.poleTargetMesh.computeWorldMatrix(true);
  77158. }
  77159. else if (options.poleTargetBone) {
  77160. this.poleTargetBone = options.poleTargetBone;
  77161. }
  77162. else if (this._bone1.getParent()) {
  77163. this.poleTargetBone = this._bone1.getParent();
  77164. }
  77165. if (options.poleTargetLocalOffset) {
  77166. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  77167. }
  77168. if (options.poleAngle) {
  77169. this.poleAngle = options.poleAngle;
  77170. }
  77171. if (options.bendAxis) {
  77172. this._bendAxis.copyFrom(options.bendAxis);
  77173. }
  77174. if (options.maxAngle) {
  77175. this.maxAngle = options.maxAngle;
  77176. }
  77177. if (options.slerpAmount) {
  77178. this.slerpAmount = options.slerpAmount;
  77179. }
  77180. }
  77181. }
  77182. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  77183. get: function () {
  77184. return this._maxAngle;
  77185. },
  77186. set: function (value) {
  77187. this._setMaxAngle(value);
  77188. },
  77189. enumerable: true,
  77190. configurable: true
  77191. });
  77192. BoneIKController.prototype._setMaxAngle = function (ang) {
  77193. if (ang < 0) {
  77194. ang = 0;
  77195. }
  77196. if (ang > Math.PI || ang == undefined) {
  77197. ang = Math.PI;
  77198. }
  77199. this._maxAngle = ang;
  77200. var a = this._bone1Length;
  77201. var b = this._bone2Length;
  77202. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  77203. };
  77204. BoneIKController.prototype.update = function () {
  77205. var bone1 = this._bone1;
  77206. if (!bone1) {
  77207. return;
  77208. }
  77209. var target = this.targetPosition;
  77210. var poleTarget = this.poleTargetPosition;
  77211. var mat1 = BoneIKController._tmpMats[0];
  77212. var mat2 = BoneIKController._tmpMats[1];
  77213. if (this.targetMesh) {
  77214. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77215. }
  77216. if (this.poleTargetBone) {
  77217. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77218. }
  77219. else if (this.poleTargetMesh) {
  77220. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77221. }
  77222. var bonePos = BoneIKController._tmpVecs[0];
  77223. var zaxis = BoneIKController._tmpVecs[1];
  77224. var xaxis = BoneIKController._tmpVecs[2];
  77225. var yaxis = BoneIKController._tmpVecs[3];
  77226. var upAxis = BoneIKController._tmpVecs[4];
  77227. var _tmpQuat = BoneIKController._tmpQuat;
  77228. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77229. poleTarget.subtractToRef(bonePos, upAxis);
  77230. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77231. upAxis.y = 1;
  77232. }
  77233. else {
  77234. upAxis.normalize();
  77235. }
  77236. target.subtractToRef(bonePos, yaxis);
  77237. yaxis.normalize();
  77238. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77239. zaxis.normalize();
  77240. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77241. xaxis.normalize();
  77242. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77243. var a = this._bone1Length;
  77244. var b = this._bone2Length;
  77245. var c = BABYLON.Vector3.Distance(bonePos, target);
  77246. if (this._maxReach > 0) {
  77247. c = Math.min(this._maxReach, c);
  77248. }
  77249. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77250. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77251. if (acosa > 1) {
  77252. acosa = 1;
  77253. }
  77254. if (acosb > 1) {
  77255. acosb = 1;
  77256. }
  77257. if (acosa < -1) {
  77258. acosa = -1;
  77259. }
  77260. if (acosb < -1) {
  77261. acosb = -1;
  77262. }
  77263. var angA = Math.acos(acosa);
  77264. var angB = Math.acos(acosb);
  77265. var angC = -angA - angB;
  77266. if (this._rightHandedSystem) {
  77267. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77268. mat2.multiplyToRef(mat1, mat1);
  77269. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77270. mat2.multiplyToRef(mat1, mat1);
  77271. }
  77272. else {
  77273. var _tmpVec = BoneIKController._tmpVecs[5];
  77274. _tmpVec.copyFrom(this._bendAxis);
  77275. _tmpVec.x *= -1;
  77276. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77277. mat2.multiplyToRef(mat1, mat1);
  77278. }
  77279. if (this.poleAngle) {
  77280. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77281. mat1.multiplyToRef(mat2, mat1);
  77282. }
  77283. if (this._bone1) {
  77284. if (this.slerpAmount < 1) {
  77285. if (!this._slerping) {
  77286. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77287. }
  77288. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77289. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77290. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77291. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77292. this._slerping = true;
  77293. }
  77294. else {
  77295. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77296. this._bone1Mat.copyFrom(mat1);
  77297. this._slerping = false;
  77298. }
  77299. }
  77300. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77301. this._bone2Ang = angC;
  77302. };
  77303. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77304. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77305. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77306. return BoneIKController;
  77307. }());
  77308. BABYLON.BoneIKController = BoneIKController;
  77309. })(BABYLON || (BABYLON = {}));
  77310. //# sourceMappingURL=babylon.boneIKController.js.map
  77311. "use strict";
  77312. var BABYLON;
  77313. (function (BABYLON) {
  77314. var BoneLookController = /** @class */ (function () {
  77315. /**
  77316. * Create a BoneLookController
  77317. * @param mesh the mesh that the bone belongs to
  77318. * @param bone the bone that will be looking to the target
  77319. * @param target the target Vector3 to look at
  77320. * @param settings optional settings:
  77321. * - maxYaw: the maximum angle the bone will yaw to
  77322. * - minYaw: the minimum angle the bone will yaw to
  77323. * - maxPitch: the maximum angle the bone will pitch to
  77324. * - minPitch: the minimum angle the bone will yaw to
  77325. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77326. * - upAxis: the up axis of the coordinate system
  77327. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77328. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  77329. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77330. * - adjustYaw: used to make an adjustment to the yaw of the bone
  77331. * - adjustPitch: used to make an adjustment to the pitch of the bone
  77332. * - adjustRoll: used to make an adjustment to the roll of the bone
  77333. **/
  77334. function BoneLookController(mesh, bone, target, options) {
  77335. /**
  77336. * The up axis of the coordinate system that is used when the bone is rotated.
  77337. */
  77338. this.upAxis = BABYLON.Vector3.Up();
  77339. /**
  77340. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77341. */
  77342. this.upAxisSpace = BABYLON.Space.LOCAL;
  77343. /**
  77344. * Used to make an adjustment to the yaw of the bone.
  77345. */
  77346. this.adjustYaw = 0;
  77347. /**
  77348. * Used to make an adjustment to the pitch of the bone.
  77349. */
  77350. this.adjustPitch = 0;
  77351. /**
  77352. * Used to make an adjustment to the roll of the bone.
  77353. */
  77354. this.adjustRoll = 0;
  77355. /**
  77356. * 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).
  77357. */
  77358. this.slerpAmount = 1;
  77359. this._boneQuat = BABYLON.Quaternion.Identity();
  77360. this._slerping = false;
  77361. this._firstFrameSkipped = false;
  77362. this._fowardAxis = BABYLON.Vector3.Forward();
  77363. this.mesh = mesh;
  77364. this.bone = bone;
  77365. this.target = target;
  77366. if (options) {
  77367. if (options.adjustYaw) {
  77368. this.adjustYaw = options.adjustYaw;
  77369. }
  77370. if (options.adjustPitch) {
  77371. this.adjustPitch = options.adjustPitch;
  77372. }
  77373. if (options.adjustRoll) {
  77374. this.adjustRoll = options.adjustRoll;
  77375. }
  77376. if (options.maxYaw != null) {
  77377. this.maxYaw = options.maxYaw;
  77378. }
  77379. else {
  77380. this.maxYaw = Math.PI;
  77381. }
  77382. if (options.minYaw != null) {
  77383. this.minYaw = options.minYaw;
  77384. }
  77385. else {
  77386. this.minYaw = -Math.PI;
  77387. }
  77388. if (options.maxPitch != null) {
  77389. this.maxPitch = options.maxPitch;
  77390. }
  77391. else {
  77392. this.maxPitch = Math.PI;
  77393. }
  77394. if (options.minPitch != null) {
  77395. this.minPitch = options.minPitch;
  77396. }
  77397. else {
  77398. this.minPitch = -Math.PI;
  77399. }
  77400. if (options.slerpAmount != null) {
  77401. this.slerpAmount = options.slerpAmount;
  77402. }
  77403. if (options.upAxis != null) {
  77404. this.upAxis = options.upAxis;
  77405. }
  77406. if (options.upAxisSpace != null) {
  77407. this.upAxisSpace = options.upAxisSpace;
  77408. }
  77409. if (options.yawAxis != null || options.pitchAxis != null) {
  77410. var newYawAxis = BABYLON.Axis.Y;
  77411. var newPitchAxis = BABYLON.Axis.X;
  77412. if (options.yawAxis != null) {
  77413. newYawAxis = options.yawAxis.clone();
  77414. newYawAxis.normalize();
  77415. }
  77416. if (options.pitchAxis != null) {
  77417. newPitchAxis = options.pitchAxis.clone();
  77418. newPitchAxis.normalize();
  77419. }
  77420. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  77421. this._transformYawPitch = BABYLON.Matrix.Identity();
  77422. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  77423. this._transformYawPitchInv = this._transformYawPitch.clone();
  77424. this._transformYawPitch.invert();
  77425. }
  77426. }
  77427. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  77428. this.upAxisSpace = BABYLON.Space.LOCAL;
  77429. }
  77430. }
  77431. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  77432. /**
  77433. * Get/set the minimum yaw angle that the bone can look to.
  77434. */
  77435. get: function () {
  77436. return this._minYaw;
  77437. },
  77438. set: function (value) {
  77439. this._minYaw = value;
  77440. this._minYawSin = Math.sin(value);
  77441. this._minYawCos = Math.cos(value);
  77442. if (this._maxYaw != null) {
  77443. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77444. this._yawRange = this._maxYaw - this._minYaw;
  77445. }
  77446. },
  77447. enumerable: true,
  77448. configurable: true
  77449. });
  77450. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  77451. /**
  77452. * Get/set the maximum yaw angle that the bone can look to.
  77453. */
  77454. get: function () {
  77455. return this._maxYaw;
  77456. },
  77457. set: function (value) {
  77458. this._maxYaw = value;
  77459. this._maxYawSin = Math.sin(value);
  77460. this._maxYawCos = Math.cos(value);
  77461. if (this._minYaw != null) {
  77462. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77463. this._yawRange = this._maxYaw - this._minYaw;
  77464. }
  77465. },
  77466. enumerable: true,
  77467. configurable: true
  77468. });
  77469. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  77470. /**
  77471. * Get/set the minimum pitch angle that the bone can look to.
  77472. */
  77473. get: function () {
  77474. return this._minPitch;
  77475. },
  77476. set: function (value) {
  77477. this._minPitch = value;
  77478. this._minPitchTan = Math.tan(value);
  77479. },
  77480. enumerable: true,
  77481. configurable: true
  77482. });
  77483. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  77484. /**
  77485. * Get/set the maximum pitch angle that the bone can look to.
  77486. */
  77487. get: function () {
  77488. return this._maxPitch;
  77489. },
  77490. set: function (value) {
  77491. this._maxPitch = value;
  77492. this._maxPitchTan = Math.tan(value);
  77493. },
  77494. enumerable: true,
  77495. configurable: true
  77496. });
  77497. /**
  77498. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  77499. */
  77500. BoneLookController.prototype.update = function () {
  77501. //skip the first frame when slerping so that the mesh rotation is correct
  77502. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  77503. this._firstFrameSkipped = true;
  77504. return;
  77505. }
  77506. var bone = this.bone;
  77507. var bonePos = BoneLookController._tmpVecs[0];
  77508. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  77509. var target = this.target;
  77510. var _tmpMat1 = BoneLookController._tmpMats[0];
  77511. var _tmpMat2 = BoneLookController._tmpMats[1];
  77512. var mesh = this.mesh;
  77513. var parentBone = bone.getParent();
  77514. var upAxis = BoneLookController._tmpVecs[1];
  77515. upAxis.copyFrom(this.upAxis);
  77516. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  77517. if (this._transformYawPitch) {
  77518. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  77519. }
  77520. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  77521. }
  77522. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  77523. mesh.getDirectionToRef(upAxis, upAxis);
  77524. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  77525. upAxis.normalize();
  77526. }
  77527. }
  77528. var checkYaw = false;
  77529. var checkPitch = false;
  77530. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  77531. checkYaw = true;
  77532. }
  77533. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  77534. checkPitch = true;
  77535. }
  77536. if (checkYaw || checkPitch) {
  77537. var spaceMat = BoneLookController._tmpMats[2];
  77538. var spaceMatInv = BoneLookController._tmpMats[3];
  77539. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  77540. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  77541. }
  77542. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  77543. spaceMat.copyFrom(mesh.getWorldMatrix());
  77544. }
  77545. else {
  77546. var forwardAxis = BoneLookController._tmpVecs[2];
  77547. forwardAxis.copyFrom(this._fowardAxis);
  77548. if (this._transformYawPitch) {
  77549. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  77550. }
  77551. if (parentBone) {
  77552. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  77553. }
  77554. else {
  77555. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  77556. }
  77557. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  77558. rightAxis.normalize();
  77559. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  77560. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  77561. }
  77562. spaceMat.invertToRef(spaceMatInv);
  77563. var xzlen = null;
  77564. if (checkPitch) {
  77565. var localTarget = BoneLookController._tmpVecs[3];
  77566. target.subtractToRef(bonePos, localTarget);
  77567. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77568. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77569. var pitch = Math.atan2(localTarget.y, xzlen);
  77570. var newPitch = pitch;
  77571. if (pitch > this._maxPitch) {
  77572. localTarget.y = this._maxPitchTan * xzlen;
  77573. newPitch = this._maxPitch;
  77574. }
  77575. else if (pitch < this._minPitch) {
  77576. localTarget.y = this._minPitchTan * xzlen;
  77577. newPitch = this._minPitch;
  77578. }
  77579. if (pitch != newPitch) {
  77580. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77581. localTarget.addInPlace(bonePos);
  77582. target = localTarget;
  77583. }
  77584. }
  77585. if (checkYaw) {
  77586. var localTarget = BoneLookController._tmpVecs[4];
  77587. target.subtractToRef(bonePos, localTarget);
  77588. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77589. var yaw = Math.atan2(localTarget.x, localTarget.z);
  77590. var newYaw = yaw;
  77591. if (yaw > this._maxYaw || yaw < this._minYaw) {
  77592. if (xzlen == null) {
  77593. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77594. }
  77595. if (this._yawRange > Math.PI) {
  77596. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  77597. localTarget.z = this._maxYawCos * xzlen;
  77598. localTarget.x = this._maxYawSin * xzlen;
  77599. newYaw = this._maxYaw;
  77600. }
  77601. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  77602. localTarget.z = this._minYawCos * xzlen;
  77603. localTarget.x = this._minYawSin * xzlen;
  77604. newYaw = this._minYaw;
  77605. }
  77606. }
  77607. else {
  77608. if (yaw > this._maxYaw) {
  77609. localTarget.z = this._maxYawCos * xzlen;
  77610. localTarget.x = this._maxYawSin * xzlen;
  77611. newYaw = this._maxYaw;
  77612. }
  77613. else if (yaw < this._minYaw) {
  77614. localTarget.z = this._minYawCos * xzlen;
  77615. localTarget.x = this._minYawSin * xzlen;
  77616. newYaw = this._minYaw;
  77617. }
  77618. }
  77619. }
  77620. if (this._slerping && this._yawRange > Math.PI) {
  77621. //are we going to be crossing into the min/max region?
  77622. var boneFwd = BoneLookController._tmpVecs[8];
  77623. boneFwd.copyFrom(BABYLON.Axis.Z);
  77624. if (this._transformYawPitch) {
  77625. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  77626. }
  77627. var boneRotMat = BoneLookController._tmpMats[4];
  77628. this._boneQuat.toRotationMatrix(boneRotMat);
  77629. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  77630. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  77631. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  77632. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  77633. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  77634. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  77635. if (angBtwTar > angBtwMidYaw) {
  77636. if (xzlen == null) {
  77637. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77638. }
  77639. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  77640. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  77641. if (angBtwMin < angBtwMax) {
  77642. newYaw = boneYaw + Math.PI * .75;
  77643. localTarget.z = Math.cos(newYaw) * xzlen;
  77644. localTarget.x = Math.sin(newYaw) * xzlen;
  77645. }
  77646. else {
  77647. newYaw = boneYaw - Math.PI * .75;
  77648. localTarget.z = Math.cos(newYaw) * xzlen;
  77649. localTarget.x = Math.sin(newYaw) * xzlen;
  77650. }
  77651. }
  77652. }
  77653. if (yaw != newYaw) {
  77654. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77655. localTarget.addInPlace(bonePos);
  77656. target = localTarget;
  77657. }
  77658. }
  77659. }
  77660. var zaxis = BoneLookController._tmpVecs[5];
  77661. var xaxis = BoneLookController._tmpVecs[6];
  77662. var yaxis = BoneLookController._tmpVecs[7];
  77663. var _tmpQuat = BoneLookController._tmpQuat;
  77664. target.subtractToRef(bonePos, zaxis);
  77665. zaxis.normalize();
  77666. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  77667. xaxis.normalize();
  77668. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  77669. yaxis.normalize();
  77670. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  77671. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  77672. return;
  77673. }
  77674. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  77675. return;
  77676. }
  77677. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  77678. return;
  77679. }
  77680. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  77681. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  77682. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  77683. }
  77684. if (this.slerpAmount < 1) {
  77685. if (!this._slerping) {
  77686. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  77687. }
  77688. if (this._transformYawPitch) {
  77689. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77690. }
  77691. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  77692. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  77693. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  77694. this._slerping = true;
  77695. }
  77696. else {
  77697. if (this._transformYawPitch) {
  77698. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77699. }
  77700. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  77701. this._slerping = false;
  77702. }
  77703. };
  77704. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  77705. var angDiff = ang2 - ang1;
  77706. angDiff %= Math.PI * 2;
  77707. if (angDiff > Math.PI) {
  77708. angDiff -= Math.PI * 2;
  77709. }
  77710. else if (angDiff < -Math.PI) {
  77711. angDiff += Math.PI * 2;
  77712. }
  77713. return angDiff;
  77714. };
  77715. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  77716. ang1 %= (2 * Math.PI);
  77717. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77718. ang2 %= (2 * Math.PI);
  77719. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77720. var ab = 0;
  77721. if (ang1 < ang2) {
  77722. ab = ang2 - ang1;
  77723. }
  77724. else {
  77725. ab = ang1 - ang2;
  77726. }
  77727. if (ab > Math.PI) {
  77728. ab = Math.PI * 2 - ab;
  77729. }
  77730. return ab;
  77731. };
  77732. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  77733. ang %= (2 * Math.PI);
  77734. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  77735. ang1 %= (2 * Math.PI);
  77736. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77737. ang2 %= (2 * Math.PI);
  77738. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77739. if (ang1 < ang2) {
  77740. if (ang > ang1 && ang < ang2) {
  77741. return true;
  77742. }
  77743. }
  77744. else {
  77745. if (ang > ang2 && ang < ang1) {
  77746. return true;
  77747. }
  77748. }
  77749. return false;
  77750. };
  77751. 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()];
  77752. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  77753. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77754. return BoneLookController;
  77755. }());
  77756. BABYLON.BoneLookController = BoneLookController;
  77757. })(BABYLON || (BABYLON = {}));
  77758. //# sourceMappingURL=babylon.boneLookController.js.map
  77759. "use strict";
  77760. var BABYLON;
  77761. (function (BABYLON) {
  77762. var Skeleton = /** @class */ (function () {
  77763. function Skeleton(name, id, scene) {
  77764. this.name = name;
  77765. this.id = id;
  77766. this.bones = new Array();
  77767. this.needInitialSkinMatrix = false;
  77768. this._isDirty = true;
  77769. this._meshesWithPoseMatrix = new Array();
  77770. this._identity = BABYLON.Matrix.Identity();
  77771. this._ranges = {};
  77772. this._lastAbsoluteTransformsUpdateId = -1;
  77773. /**
  77774. * Specifies if the skeleton should be serialized.
  77775. */
  77776. this.doNotSerialize = false;
  77777. // Events
  77778. /**
  77779. * An event triggered before computing the skeleton's matrices
  77780. */
  77781. this.onBeforeComputeObservable = new BABYLON.Observable();
  77782. this.bones = [];
  77783. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77784. scene.skeletons.push(this);
  77785. //make sure it will recalculate the matrix next time prepare is called.
  77786. this._isDirty = true;
  77787. }
  77788. // Members
  77789. Skeleton.prototype.getTransformMatrices = function (mesh) {
  77790. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  77791. return mesh._bonesTransformMatrices;
  77792. }
  77793. if (!this._transformMatrices) {
  77794. this.prepare();
  77795. }
  77796. return this._transformMatrices;
  77797. };
  77798. Skeleton.prototype.getScene = function () {
  77799. return this._scene;
  77800. };
  77801. // Methods
  77802. /**
  77803. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  77804. */
  77805. Skeleton.prototype.toString = function (fullDetails) {
  77806. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  77807. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  77808. if (fullDetails) {
  77809. ret += ", Ranges: {";
  77810. var first = true;
  77811. for (var name_1 in this._ranges) {
  77812. if (first) {
  77813. ret += ", ";
  77814. first = false;
  77815. }
  77816. ret += name_1;
  77817. }
  77818. ret += "}";
  77819. }
  77820. return ret;
  77821. };
  77822. /**
  77823. * Get bone's index searching by name
  77824. * @param {string} name is bone's name to search for
  77825. * @return {number} Indice of the bone. Returns -1 if not found
  77826. */
  77827. Skeleton.prototype.getBoneIndexByName = function (name) {
  77828. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  77829. if (this.bones[boneIndex].name === name) {
  77830. return boneIndex;
  77831. }
  77832. }
  77833. return -1;
  77834. };
  77835. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  77836. // check name not already in use
  77837. if (!this._ranges[name]) {
  77838. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  77839. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77840. if (this.bones[i].animations[0]) {
  77841. this.bones[i].animations[0].createRange(name, from, to);
  77842. }
  77843. }
  77844. }
  77845. };
  77846. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  77847. if (deleteFrames === void 0) { deleteFrames = true; }
  77848. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77849. if (this.bones[i].animations[0]) {
  77850. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  77851. }
  77852. }
  77853. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  77854. };
  77855. Skeleton.prototype.getAnimationRange = function (name) {
  77856. return this._ranges[name];
  77857. };
  77858. /**
  77859. * Returns as an Array, all AnimationRanges defined on this skeleton
  77860. */
  77861. Skeleton.prototype.getAnimationRanges = function () {
  77862. var animationRanges = [];
  77863. var name;
  77864. var i = 0;
  77865. for (name in this._ranges) {
  77866. animationRanges[i] = this._ranges[name];
  77867. i++;
  77868. }
  77869. return animationRanges;
  77870. };
  77871. /**
  77872. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  77873. */
  77874. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  77875. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77876. if (this._ranges[name] || !source.getAnimationRange(name)) {
  77877. return false;
  77878. }
  77879. var ret = true;
  77880. var frameOffset = this._getHighestAnimationFrame() + 1;
  77881. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  77882. var boneDict = {};
  77883. var sourceBones = source.bones;
  77884. var nBones;
  77885. var i;
  77886. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  77887. boneDict[sourceBones[i].name] = sourceBones[i];
  77888. }
  77889. if (this.bones.length !== sourceBones.length) {
  77890. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  77891. ret = false;
  77892. }
  77893. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  77894. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  77895. var boneName = this.bones[i].name;
  77896. var sourceBone = boneDict[boneName];
  77897. if (sourceBone) {
  77898. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  77899. }
  77900. else {
  77901. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  77902. ret = false;
  77903. }
  77904. }
  77905. // do not call createAnimationRange(), since it also is done to bones, which was already done
  77906. var range = source.getAnimationRange(name);
  77907. if (range) {
  77908. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  77909. }
  77910. return ret;
  77911. };
  77912. Skeleton.prototype.returnToRest = function () {
  77913. for (var index = 0; index < this.bones.length; index++) {
  77914. this.bones[index].returnToRest();
  77915. }
  77916. };
  77917. Skeleton.prototype._getHighestAnimationFrame = function () {
  77918. var ret = 0;
  77919. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77920. if (this.bones[i].animations[0]) {
  77921. var highest = this.bones[i].animations[0].getHighestFrame();
  77922. if (ret < highest) {
  77923. ret = highest;
  77924. }
  77925. }
  77926. }
  77927. return ret;
  77928. };
  77929. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  77930. var range = this.getAnimationRange(name);
  77931. if (!range) {
  77932. return null;
  77933. }
  77934. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  77935. };
  77936. Skeleton.prototype._markAsDirty = function () {
  77937. this._isDirty = true;
  77938. };
  77939. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  77940. this._meshesWithPoseMatrix.push(mesh);
  77941. };
  77942. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  77943. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  77944. if (index > -1) {
  77945. this._meshesWithPoseMatrix.splice(index, 1);
  77946. }
  77947. };
  77948. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  77949. this.onBeforeComputeObservable.notifyObservers(this);
  77950. for (var index = 0; index < this.bones.length; index++) {
  77951. var bone = this.bones[index];
  77952. var parentBone = bone.getParent();
  77953. if (parentBone) {
  77954. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  77955. }
  77956. else {
  77957. if (initialSkinMatrix) {
  77958. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  77959. }
  77960. else {
  77961. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  77962. }
  77963. }
  77964. if (bone._index !== -1) {
  77965. var mappedIndex = bone._index === null ? index : bone._index;
  77966. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  77967. }
  77968. }
  77969. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  77970. };
  77971. Skeleton.prototype.prepare = function () {
  77972. if (!this._isDirty) {
  77973. return;
  77974. }
  77975. if (this.needInitialSkinMatrix) {
  77976. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  77977. var mesh = this._meshesWithPoseMatrix[index];
  77978. var poseMatrix = mesh.getPoseMatrix();
  77979. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  77980. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77981. }
  77982. if (this._synchronizedWithMesh !== mesh) {
  77983. this._synchronizedWithMesh = mesh;
  77984. // Prepare bones
  77985. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  77986. var bone = this.bones[boneIndex];
  77987. if (!bone.getParent()) {
  77988. var matrix = bone.getBaseMatrix();
  77989. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  77990. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  77991. }
  77992. }
  77993. }
  77994. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  77995. }
  77996. }
  77997. else {
  77998. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  77999. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78000. }
  78001. this._computeTransformMatrices(this._transformMatrices, null);
  78002. }
  78003. this._isDirty = false;
  78004. this._scene._activeBones.addCount(this.bones.length, false);
  78005. };
  78006. Skeleton.prototype.getAnimatables = function () {
  78007. if (!this._animatables || this._animatables.length !== this.bones.length) {
  78008. this._animatables = [];
  78009. for (var index = 0; index < this.bones.length; index++) {
  78010. this._animatables.push(this.bones[index]);
  78011. }
  78012. }
  78013. return this._animatables;
  78014. };
  78015. Skeleton.prototype.clone = function (name, id) {
  78016. var result = new Skeleton(name, id || name, this._scene);
  78017. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78018. for (var index = 0; index < this.bones.length; index++) {
  78019. var source = this.bones[index];
  78020. var parentBone = null;
  78021. var parent_1 = source.getParent();
  78022. if (parent_1) {
  78023. var parentIndex = this.bones.indexOf(parent_1);
  78024. parentBone = result.bones[parentIndex];
  78025. }
  78026. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  78027. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  78028. }
  78029. if (this._ranges) {
  78030. result._ranges = {};
  78031. for (var rangeName in this._ranges) {
  78032. var range = this._ranges[rangeName];
  78033. if (range) {
  78034. result._ranges[rangeName] = range.clone();
  78035. }
  78036. }
  78037. }
  78038. this._isDirty = true;
  78039. return result;
  78040. };
  78041. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  78042. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  78043. this.bones.forEach(function (bone) {
  78044. bone.animations.forEach(function (animation) {
  78045. animation.enableBlending = true;
  78046. animation.blendingSpeed = blendingSpeed;
  78047. });
  78048. });
  78049. };
  78050. Skeleton.prototype.dispose = function () {
  78051. this._meshesWithPoseMatrix = [];
  78052. // Animations
  78053. this.getScene().stopAnimation(this);
  78054. // Remove from scene
  78055. this.getScene().removeSkeleton(this);
  78056. };
  78057. Skeleton.prototype.serialize = function () {
  78058. var serializationObject = {};
  78059. serializationObject.name = this.name;
  78060. serializationObject.id = this.id;
  78061. if (this.dimensionsAtRest) {
  78062. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  78063. }
  78064. serializationObject.bones = [];
  78065. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78066. for (var index = 0; index < this.bones.length; index++) {
  78067. var bone = this.bones[index];
  78068. var parent_2 = bone.getParent();
  78069. var serializedBone = {
  78070. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  78071. name: bone.name,
  78072. matrix: bone.getBaseMatrix().toArray(),
  78073. rest: bone.getRestPose().toArray()
  78074. };
  78075. serializationObject.bones.push(serializedBone);
  78076. if (bone.length) {
  78077. serializedBone.length = bone.length;
  78078. }
  78079. if (bone.animations && bone.animations.length > 0) {
  78080. serializedBone.animation = bone.animations[0].serialize();
  78081. }
  78082. serializationObject.ranges = [];
  78083. for (var name in this._ranges) {
  78084. var source = this._ranges[name];
  78085. if (!source) {
  78086. continue;
  78087. }
  78088. var range = {};
  78089. range.name = name;
  78090. range.from = source.from;
  78091. range.to = source.to;
  78092. serializationObject.ranges.push(range);
  78093. }
  78094. }
  78095. return serializationObject;
  78096. };
  78097. Skeleton.Parse = function (parsedSkeleton, scene) {
  78098. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  78099. if (parsedSkeleton.dimensionsAtRest) {
  78100. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  78101. }
  78102. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  78103. var index;
  78104. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  78105. var parsedBone = parsedSkeleton.bones[index];
  78106. var parentBone = null;
  78107. if (parsedBone.parentBoneIndex > -1) {
  78108. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  78109. }
  78110. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  78111. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  78112. if (parsedBone.length) {
  78113. bone.length = parsedBone.length;
  78114. }
  78115. if (parsedBone.animation) {
  78116. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  78117. }
  78118. }
  78119. // placed after bones, so createAnimationRange can cascade down
  78120. if (parsedSkeleton.ranges) {
  78121. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  78122. var data = parsedSkeleton.ranges[index];
  78123. skeleton.createAnimationRange(data.name, data.from, data.to);
  78124. }
  78125. }
  78126. return skeleton;
  78127. };
  78128. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  78129. if (forceUpdate === void 0) { forceUpdate = false; }
  78130. var renderId = this._scene.getRenderId();
  78131. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  78132. this.bones[0].computeAbsoluteTransforms();
  78133. this._lastAbsoluteTransformsUpdateId = renderId;
  78134. }
  78135. };
  78136. Skeleton.prototype.getPoseMatrix = function () {
  78137. var poseMatrix = null;
  78138. if (this._meshesWithPoseMatrix.length > 0) {
  78139. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  78140. }
  78141. return poseMatrix;
  78142. };
  78143. Skeleton.prototype.sortBones = function () {
  78144. var bones = new Array();
  78145. var visited = new Array(this.bones.length);
  78146. for (var index = 0; index < this.bones.length; index++) {
  78147. this._sortBones(index, bones, visited);
  78148. }
  78149. this.bones = bones;
  78150. };
  78151. Skeleton.prototype._sortBones = function (index, bones, visited) {
  78152. if (visited[index]) {
  78153. return;
  78154. }
  78155. visited[index] = true;
  78156. var bone = this.bones[index];
  78157. if (bone._index === undefined) {
  78158. bone._index = index;
  78159. }
  78160. var parentBone = bone.getParent();
  78161. if (parentBone) {
  78162. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  78163. }
  78164. bones.push(bone);
  78165. };
  78166. return Skeleton;
  78167. }());
  78168. BABYLON.Skeleton = Skeleton;
  78169. })(BABYLON || (BABYLON = {}));
  78170. //# sourceMappingURL=babylon.skeleton.js.map
  78171. "use strict";
  78172. var BABYLON;
  78173. (function (BABYLON) {
  78174. var SphericalPolynomial = /** @class */ (function () {
  78175. function SphericalPolynomial() {
  78176. this.x = BABYLON.Vector3.Zero();
  78177. this.y = BABYLON.Vector3.Zero();
  78178. this.z = BABYLON.Vector3.Zero();
  78179. this.xx = BABYLON.Vector3.Zero();
  78180. this.yy = BABYLON.Vector3.Zero();
  78181. this.zz = BABYLON.Vector3.Zero();
  78182. this.xy = BABYLON.Vector3.Zero();
  78183. this.yz = BABYLON.Vector3.Zero();
  78184. this.zx = BABYLON.Vector3.Zero();
  78185. }
  78186. SphericalPolynomial.prototype.addAmbient = function (color) {
  78187. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78188. this.xx = this.xx.add(colorVector);
  78189. this.yy = this.yy.add(colorVector);
  78190. this.zz = this.zz.add(colorVector);
  78191. };
  78192. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  78193. var result = new SphericalPolynomial();
  78194. result.x = harmonics.L11.scale(1.02333);
  78195. result.y = harmonics.L1_1.scale(1.02333);
  78196. result.z = harmonics.L10.scale(1.02333);
  78197. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  78198. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  78199. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  78200. result.yz = harmonics.L2_1.scale(0.858086);
  78201. result.zx = harmonics.L21.scale(0.858086);
  78202. result.xy = harmonics.L2_2.scale(0.858086);
  78203. result.scale(1.0 / Math.PI);
  78204. return result;
  78205. };
  78206. SphericalPolynomial.prototype.scale = function (scale) {
  78207. this.x = this.x.scale(scale);
  78208. this.y = this.y.scale(scale);
  78209. this.z = this.z.scale(scale);
  78210. this.xx = this.xx.scale(scale);
  78211. this.yy = this.yy.scale(scale);
  78212. this.zz = this.zz.scale(scale);
  78213. this.yz = this.yz.scale(scale);
  78214. this.zx = this.zx.scale(scale);
  78215. this.xy = this.xy.scale(scale);
  78216. };
  78217. return SphericalPolynomial;
  78218. }());
  78219. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78220. var SphericalHarmonics = /** @class */ (function () {
  78221. function SphericalHarmonics() {
  78222. this.L00 = BABYLON.Vector3.Zero();
  78223. this.L1_1 = BABYLON.Vector3.Zero();
  78224. this.L10 = BABYLON.Vector3.Zero();
  78225. this.L11 = BABYLON.Vector3.Zero();
  78226. this.L2_2 = BABYLON.Vector3.Zero();
  78227. this.L2_1 = BABYLON.Vector3.Zero();
  78228. this.L20 = BABYLON.Vector3.Zero();
  78229. this.L21 = BABYLON.Vector3.Zero();
  78230. this.L22 = BABYLON.Vector3.Zero();
  78231. }
  78232. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78233. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78234. var c = colorVector.scale(deltaSolidAngle);
  78235. this.L00 = this.L00.add(c.scale(0.282095));
  78236. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78237. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78238. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78239. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78240. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78241. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78242. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78243. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78244. };
  78245. SphericalHarmonics.prototype.scale = function (scale) {
  78246. this.L00 = this.L00.scale(scale);
  78247. this.L1_1 = this.L1_1.scale(scale);
  78248. this.L10 = this.L10.scale(scale);
  78249. this.L11 = this.L11.scale(scale);
  78250. this.L2_2 = this.L2_2.scale(scale);
  78251. this.L2_1 = this.L2_1.scale(scale);
  78252. this.L20 = this.L20.scale(scale);
  78253. this.L21 = this.L21.scale(scale);
  78254. this.L22 = this.L22.scale(scale);
  78255. };
  78256. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  78257. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  78258. //
  78259. // E_lm = A_l * L_lm
  78260. //
  78261. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  78262. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  78263. // the scaling factors are given in equation 9.
  78264. // Constant (Band 0)
  78265. this.L00 = this.L00.scale(3.141593);
  78266. // Linear (Band 1)
  78267. this.L1_1 = this.L1_1.scale(2.094395);
  78268. this.L10 = this.L10.scale(2.094395);
  78269. this.L11 = this.L11.scale(2.094395);
  78270. // Quadratic (Band 2)
  78271. this.L2_2 = this.L2_2.scale(0.785398);
  78272. this.L2_1 = this.L2_1.scale(0.785398);
  78273. this.L20 = this.L20.scale(0.785398);
  78274. this.L21 = this.L21.scale(0.785398);
  78275. this.L22 = this.L22.scale(0.785398);
  78276. };
  78277. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  78278. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  78279. // L = (1/pi) * E * rho
  78280. //
  78281. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  78282. this.scale(1.0 / Math.PI);
  78283. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  78284. // (The pixel shader must apply albedo after texture fetches, etc).
  78285. };
  78286. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  78287. var result = new SphericalHarmonics();
  78288. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  78289. result.L1_1 = polynomial.y.scale(0.977204);
  78290. result.L10 = polynomial.z.scale(0.977204);
  78291. result.L11 = polynomial.x.scale(0.977204);
  78292. result.L2_2 = polynomial.xy.scale(1.16538);
  78293. result.L2_1 = polynomial.yz.scale(1.16538);
  78294. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  78295. result.L21 = polynomial.zx.scale(1.16538);
  78296. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  78297. result.scale(Math.PI);
  78298. return result;
  78299. };
  78300. return SphericalHarmonics;
  78301. }());
  78302. BABYLON.SphericalHarmonics = SphericalHarmonics;
  78303. })(BABYLON || (BABYLON = {}));
  78304. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  78305. "use strict";
  78306. var BABYLON;
  78307. (function (BABYLON) {
  78308. var FileFaceOrientation = /** @class */ (function () {
  78309. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  78310. this.name = name;
  78311. this.worldAxisForNormal = worldAxisForNormal;
  78312. this.worldAxisForFileX = worldAxisForFileX;
  78313. this.worldAxisForFileY = worldAxisForFileY;
  78314. }
  78315. return FileFaceOrientation;
  78316. }());
  78317. ;
  78318. /**
  78319. * Helper class dealing with the extraction of spherical polynomial dataArray
  78320. * from a cube map.
  78321. */
  78322. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  78323. function CubeMapToSphericalPolynomialTools() {
  78324. }
  78325. /**
  78326. * Converts a texture to the according Spherical Polynomial data.
  78327. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78328. *
  78329. * @param texture The texture to extract the information from.
  78330. * @return The Spherical Polynomial data.
  78331. */
  78332. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  78333. if (!texture.isCube) {
  78334. // Only supports cube Textures currently.
  78335. return null;
  78336. }
  78337. var size = texture.getSize().width;
  78338. var right = texture.readPixels(0);
  78339. var left = texture.readPixels(1);
  78340. var up;
  78341. var down;
  78342. if (texture.isRenderTarget) {
  78343. up = texture.readPixels(3);
  78344. down = texture.readPixels(2);
  78345. }
  78346. else {
  78347. up = texture.readPixels(2);
  78348. down = texture.readPixels(3);
  78349. }
  78350. var front = texture.readPixels(4);
  78351. var back = texture.readPixels(5);
  78352. var gammaSpace = texture.gammaSpace;
  78353. // Always read as RGBA.
  78354. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  78355. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78356. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78357. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78358. }
  78359. var cubeInfo = {
  78360. size: size,
  78361. right: right,
  78362. left: left,
  78363. up: up,
  78364. down: down,
  78365. front: front,
  78366. back: back,
  78367. format: format,
  78368. type: type,
  78369. gammaSpace: gammaSpace,
  78370. };
  78371. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  78372. };
  78373. /**
  78374. * Converts a cubemap to the according Spherical Polynomial data.
  78375. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78376. *
  78377. * @param cubeInfo The Cube map to extract the information from.
  78378. * @return The Spherical Polynomial data.
  78379. */
  78380. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  78381. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  78382. var totalSolidAngle = 0.0;
  78383. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  78384. var du = 2.0 / cubeInfo.size;
  78385. var dv = du;
  78386. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  78387. var minUV = du * 0.5 - 1.0;
  78388. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78389. var fileFace = this.FileFaces[faceIndex];
  78390. var dataArray = cubeInfo[fileFace.name];
  78391. var v = minUV;
  78392. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  78393. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  78394. // Because SP is still linear, so summation is fine in that basis.
  78395. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  78396. for (var y = 0; y < cubeInfo.size; y++) {
  78397. var u = minUV;
  78398. for (var x = 0; x < cubeInfo.size; x++) {
  78399. // World direction (not normalised)
  78400. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  78401. worldDirection.normalize();
  78402. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  78403. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  78404. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  78405. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  78406. // Handle Integer types.
  78407. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78408. r /= 255;
  78409. g /= 255;
  78410. b /= 255;
  78411. }
  78412. // Handle Gamma space textures.
  78413. if (cubeInfo.gammaSpace) {
  78414. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  78415. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  78416. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  78417. }
  78418. var color = new BABYLON.Color3(r, g, b);
  78419. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  78420. totalSolidAngle += deltaSolidAngle;
  78421. u += du;
  78422. }
  78423. v += dv;
  78424. }
  78425. }
  78426. // Solid angle for entire sphere is 4*pi
  78427. var sphereSolidAngle = 4.0 * Math.PI;
  78428. // Adjust the solid angle to allow for how many faces we processed.
  78429. var facesProcessed = 6.0;
  78430. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  78431. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  78432. // This is needed because the numerical integration over the cube uses a
  78433. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  78434. // and also to compensate for accumulative error due to float precision in the summation.
  78435. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  78436. sphericalHarmonics.scale(correctionFactor);
  78437. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  78438. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  78439. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  78440. };
  78441. CubeMapToSphericalPolynomialTools.FileFaces = [
  78442. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  78443. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  78444. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  78445. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  78446. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  78447. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  78448. ];
  78449. return CubeMapToSphericalPolynomialTools;
  78450. }());
  78451. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  78452. })(BABYLON || (BABYLON = {}));
  78453. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  78454. "use strict";
  78455. var BABYLON;
  78456. (function (BABYLON) {
  78457. /**
  78458. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  78459. */
  78460. var PanoramaToCubeMapTools = /** @class */ (function () {
  78461. function PanoramaToCubeMapTools() {
  78462. }
  78463. /**
  78464. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  78465. *
  78466. * @param float32Array The source data.
  78467. * @param inputWidth The width of the input panorama.
  78468. * @param inputhHeight The height of the input panorama.
  78469. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  78470. * @return The cubemap data
  78471. */
  78472. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  78473. if (!float32Array) {
  78474. throw "ConvertPanoramaToCubemap: input cannot be null";
  78475. }
  78476. if (float32Array.length != inputWidth * inputHeight * 3) {
  78477. throw "ConvertPanoramaToCubemap: input size is wrong";
  78478. }
  78479. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  78480. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  78481. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  78482. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  78483. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  78484. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  78485. return {
  78486. front: textureFront,
  78487. back: textureBack,
  78488. left: textureLeft,
  78489. right: textureRight,
  78490. up: textureUp,
  78491. down: textureDown,
  78492. size: size,
  78493. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  78494. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  78495. gammaSpace: false,
  78496. };
  78497. };
  78498. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  78499. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  78500. var textureArray = new Float32Array(buffer);
  78501. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  78502. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  78503. var dy = 1 / texSize;
  78504. var fy = 0;
  78505. for (var y = 0; y < texSize; y++) {
  78506. var xv1 = faceData[0];
  78507. var xv2 = faceData[2];
  78508. for (var x = 0; x < texSize; x++) {
  78509. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  78510. v.normalize();
  78511. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  78512. // 3 channels per pixels
  78513. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  78514. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  78515. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  78516. xv1 = xv1.add(rotDX1);
  78517. xv2 = xv2.add(rotDX2);
  78518. }
  78519. fy += dy;
  78520. }
  78521. return textureArray;
  78522. };
  78523. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  78524. var theta = Math.atan2(vDir.z, vDir.x);
  78525. var phi = Math.acos(vDir.y);
  78526. while (theta < -Math.PI)
  78527. theta += 2 * Math.PI;
  78528. while (theta > Math.PI)
  78529. theta -= 2 * Math.PI;
  78530. var dx = theta / Math.PI;
  78531. var dy = phi / Math.PI;
  78532. // recenter.
  78533. dx = dx * 0.5 + 0.5;
  78534. var px = Math.round(dx * inputWidth);
  78535. if (px < 0)
  78536. px = 0;
  78537. else if (px >= inputWidth)
  78538. px = inputWidth - 1;
  78539. var py = Math.round(dy * inputHeight);
  78540. if (py < 0)
  78541. py = 0;
  78542. else if (py >= inputHeight)
  78543. py = inputHeight - 1;
  78544. var inputY = (inputHeight - py - 1);
  78545. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  78546. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  78547. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  78548. return {
  78549. r: r,
  78550. g: g,
  78551. b: b
  78552. };
  78553. };
  78554. PanoramaToCubeMapTools.FACE_FRONT = [
  78555. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78556. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78557. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78558. new BABYLON.Vector3(1.0, 1.0, -1.0)
  78559. ];
  78560. PanoramaToCubeMapTools.FACE_BACK = [
  78561. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78562. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78563. new BABYLON.Vector3(1.0, 1.0, 1.0),
  78564. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  78565. ];
  78566. PanoramaToCubeMapTools.FACE_RIGHT = [
  78567. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78568. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78569. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78570. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78571. ];
  78572. PanoramaToCubeMapTools.FACE_LEFT = [
  78573. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78574. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78575. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78576. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  78577. ];
  78578. PanoramaToCubeMapTools.FACE_DOWN = [
  78579. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78580. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78581. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78582. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78583. ];
  78584. PanoramaToCubeMapTools.FACE_UP = [
  78585. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78586. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78587. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78588. new BABYLON.Vector3(1.0, -1.0, -1.0)
  78589. ];
  78590. return PanoramaToCubeMapTools;
  78591. }());
  78592. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  78593. })(BABYLON || (BABYLON = {}));
  78594. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  78595. "use strict";
  78596. var BABYLON;
  78597. (function (BABYLON) {
  78598. ;
  78599. /**
  78600. * This groups tools to convert HDR texture to native colors array.
  78601. */
  78602. var HDRTools = /** @class */ (function () {
  78603. function HDRTools() {
  78604. }
  78605. HDRTools.Ldexp = function (mantissa, exponent) {
  78606. if (exponent > 1023) {
  78607. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  78608. }
  78609. if (exponent < -1074) {
  78610. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  78611. }
  78612. return mantissa * Math.pow(2, exponent);
  78613. };
  78614. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  78615. if (exponent > 0) {
  78616. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  78617. float32array[index + 0] = red * exponent;
  78618. float32array[index + 1] = green * exponent;
  78619. float32array[index + 2] = blue * exponent;
  78620. }
  78621. else {
  78622. float32array[index + 0] = 0;
  78623. float32array[index + 1] = 0;
  78624. float32array[index + 2] = 0;
  78625. }
  78626. };
  78627. HDRTools.readStringLine = function (uint8array, startIndex) {
  78628. var line = "";
  78629. var character = "";
  78630. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  78631. character = String.fromCharCode(uint8array[i]);
  78632. if (character == "\n") {
  78633. break;
  78634. }
  78635. line += character;
  78636. }
  78637. return line;
  78638. };
  78639. /**
  78640. * Reads header information from an RGBE texture stored in a native array.
  78641. * More information on this format are available here:
  78642. * https://en.wikipedia.org/wiki/RGBE_image_format
  78643. *
  78644. * @param uint8array The binary file stored in native array.
  78645. * @return The header information.
  78646. */
  78647. HDRTools.RGBE_ReadHeader = function (uint8array) {
  78648. var height = 0;
  78649. var width = 0;
  78650. var line = this.readStringLine(uint8array, 0);
  78651. if (line[0] != '#' || line[1] != '?') {
  78652. throw "Bad HDR Format.";
  78653. }
  78654. var endOfHeader = false;
  78655. var findFormat = false;
  78656. var lineIndex = 0;
  78657. do {
  78658. lineIndex += (line.length + 1);
  78659. line = this.readStringLine(uint8array, lineIndex);
  78660. if (line == "FORMAT=32-bit_rle_rgbe") {
  78661. findFormat = true;
  78662. }
  78663. else if (line.length == 0) {
  78664. endOfHeader = true;
  78665. }
  78666. } while (!endOfHeader);
  78667. if (!findFormat) {
  78668. throw "HDR Bad header format, unsupported FORMAT";
  78669. }
  78670. lineIndex += (line.length + 1);
  78671. line = this.readStringLine(uint8array, lineIndex);
  78672. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  78673. var match = sizeRegexp.exec(line);
  78674. // TODO. Support +Y and -X if needed.
  78675. if (!match || match.length < 3) {
  78676. throw "HDR Bad header format, no size";
  78677. }
  78678. width = parseInt(match[2]);
  78679. height = parseInt(match[1]);
  78680. if (width < 8 || width > 0x7fff) {
  78681. throw "HDR Bad header format, unsupported size";
  78682. }
  78683. lineIndex += (line.length + 1);
  78684. return {
  78685. height: height,
  78686. width: width,
  78687. dataPosition: lineIndex
  78688. };
  78689. };
  78690. /**
  78691. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  78692. * This RGBE texture needs to store the information as a panorama.
  78693. *
  78694. * More information on this format are available here:
  78695. * https://en.wikipedia.org/wiki/RGBE_image_format
  78696. *
  78697. * @param buffer The binary file stored in an array buffer.
  78698. * @param size The expected size of the extracted cubemap.
  78699. * @return The Cube Map information.
  78700. */
  78701. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  78702. var uint8array = new Uint8Array(buffer);
  78703. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  78704. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78705. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  78706. return cubeMapData;
  78707. };
  78708. /**
  78709. * Returns the pixels data extracted from an RGBE texture.
  78710. * This pixels will be stored left to right up to down in the R G B order in one array.
  78711. *
  78712. * More information on this format are available here:
  78713. * https://en.wikipedia.org/wiki/RGBE_image_format
  78714. *
  78715. * @param uint8array The binary file stored in an array buffer.
  78716. * @param hdrInfo The header information of the file.
  78717. * @return The pixels data in RGB right to left up to down order.
  78718. */
  78719. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  78720. // Keep for multi format supports.
  78721. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78722. };
  78723. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  78724. var num_scanlines = hdrInfo.height;
  78725. var scanline_width = hdrInfo.width;
  78726. var a, b, c, d, count;
  78727. var dataIndex = hdrInfo.dataPosition;
  78728. var index = 0, endIndex = 0, i = 0;
  78729. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  78730. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  78731. // 3 channels of 4 bytes per pixel in float.
  78732. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  78733. var resultArray = new Float32Array(resultBuffer);
  78734. // read in each successive scanline
  78735. while (num_scanlines > 0) {
  78736. a = uint8array[dataIndex++];
  78737. b = uint8array[dataIndex++];
  78738. c = uint8array[dataIndex++];
  78739. d = uint8array[dataIndex++];
  78740. if (a != 2 || b != 2 || (c & 0x80)) {
  78741. // this file is not run length encoded
  78742. throw "HDR Bad header format, not RLE";
  78743. }
  78744. if (((c << 8) | d) != scanline_width) {
  78745. throw "HDR Bad header format, wrong scan line width";
  78746. }
  78747. index = 0;
  78748. // read each of the four channels for the scanline into the buffer
  78749. for (i = 0; i < 4; i++) {
  78750. endIndex = (i + 1) * scanline_width;
  78751. while (index < endIndex) {
  78752. a = uint8array[dataIndex++];
  78753. b = uint8array[dataIndex++];
  78754. if (a > 128) {
  78755. // a run of the same value
  78756. count = a - 128;
  78757. if ((count == 0) || (count > endIndex - index)) {
  78758. throw "HDR Bad Format, bad scanline data (run)";
  78759. }
  78760. while (count-- > 0) {
  78761. scanLineArray[index++] = b;
  78762. }
  78763. }
  78764. else {
  78765. // a non-run
  78766. count = a;
  78767. if ((count == 0) || (count > endIndex - index)) {
  78768. throw "HDR Bad Format, bad scanline data (non-run)";
  78769. }
  78770. scanLineArray[index++] = b;
  78771. if (--count > 0) {
  78772. for (var j = 0; j < count; j++) {
  78773. scanLineArray[index++] = uint8array[dataIndex++];
  78774. }
  78775. }
  78776. }
  78777. }
  78778. }
  78779. // now convert data from buffer into floats
  78780. for (i = 0; i < scanline_width; i++) {
  78781. a = scanLineArray[i];
  78782. b = scanLineArray[i + scanline_width];
  78783. c = scanLineArray[i + 2 * scanline_width];
  78784. d = scanLineArray[i + 3 * scanline_width];
  78785. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  78786. }
  78787. num_scanlines--;
  78788. }
  78789. return resultArray;
  78790. };
  78791. return HDRTools;
  78792. }());
  78793. BABYLON.HDRTools = HDRTools;
  78794. })(BABYLON || (BABYLON = {}));
  78795. //# sourceMappingURL=babylon.hdr.js.map
  78796. "use strict";
  78797. var BABYLON;
  78798. (function (BABYLON) {
  78799. /**
  78800. * This represents a texture coming from an HDR input.
  78801. *
  78802. * The only supported format is currently panorama picture stored in RGBE format.
  78803. * Example of such files can be found on HDRLib: http://hdrlib.com/
  78804. */
  78805. var HDRCubeTexture = /** @class */ (function (_super) {
  78806. __extends(HDRCubeTexture, _super);
  78807. /**
  78808. * Instantiates an HDRTexture from the following parameters.
  78809. *
  78810. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  78811. * @param scene The scene the texture will be used in
  78812. * @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.
  78813. * @param noMipmap Forces to not generate the mipmap if true
  78814. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  78815. * @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)
  78816. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  78817. */
  78818. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  78819. if (noMipmap === void 0) { noMipmap = false; }
  78820. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78821. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78822. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78823. if (onLoad === void 0) { onLoad = null; }
  78824. if (onError === void 0) { onError = null; }
  78825. var _this = _super.call(this, scene) || this;
  78826. _this._useInGammaSpace = false;
  78827. _this._generateHarmonics = true;
  78828. _this._isBABYLONPreprocessed = false;
  78829. _this._onLoad = null;
  78830. _this._onError = null;
  78831. /**
  78832. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  78833. */
  78834. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  78835. /**
  78836. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  78837. * This is usefull at run time to apply the good shader.
  78838. */
  78839. _this.isPMREM = false;
  78840. _this._isBlocking = true;
  78841. _this._rotationY = 0;
  78842. /**
  78843. * Gets or sets the center of the bounding box associated with the cube texture
  78844. * It must define where the camera used to render the texture was set
  78845. */
  78846. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  78847. if (!url) {
  78848. return _this;
  78849. }
  78850. _this.name = url;
  78851. _this.url = url;
  78852. _this.hasAlpha = false;
  78853. _this.isCube = true;
  78854. _this._textureMatrix = BABYLON.Matrix.Identity();
  78855. _this._onLoad = onLoad;
  78856. _this._onError = onError;
  78857. _this.gammaSpace = false;
  78858. var caps = scene.getEngine().getCaps();
  78859. if (size) {
  78860. _this._isBABYLONPreprocessed = false;
  78861. _this._noMipmap = noMipmap;
  78862. _this._size = size;
  78863. _this._useInGammaSpace = useInGammaSpace;
  78864. _this._usePMREMGenerator = usePMREMGenerator &&
  78865. caps.textureLOD &&
  78866. caps.textureFloat &&
  78867. !_this._useInGammaSpace;
  78868. }
  78869. else {
  78870. _this._isBABYLONPreprocessed = true;
  78871. _this._noMipmap = false;
  78872. _this._useInGammaSpace = false;
  78873. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  78874. !_this._useInGammaSpace;
  78875. }
  78876. _this.isPMREM = _this._usePMREMGenerator;
  78877. _this._texture = _this._getFromCache(url, _this._noMipmap);
  78878. if (!_this._texture) {
  78879. if (!scene.useDelayedTextureLoading) {
  78880. _this.loadTexture();
  78881. }
  78882. else {
  78883. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78884. }
  78885. }
  78886. return _this;
  78887. }
  78888. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  78889. /**
  78890. * Gets wether or not the texture is blocking during loading.
  78891. */
  78892. get: function () {
  78893. return this._isBlocking;
  78894. },
  78895. /**
  78896. * Sets wether or not the texture is blocking during loading.
  78897. */
  78898. set: function (value) {
  78899. this._isBlocking = value;
  78900. },
  78901. enumerable: true,
  78902. configurable: true
  78903. });
  78904. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  78905. /**
  78906. * Gets texture matrix rotation angle around Y axis radians.
  78907. */
  78908. get: function () {
  78909. return this._rotationY;
  78910. },
  78911. /**
  78912. * Sets texture matrix rotation angle around Y axis in radians.
  78913. */
  78914. set: function (value) {
  78915. this._rotationY = value;
  78916. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  78917. },
  78918. enumerable: true,
  78919. configurable: true
  78920. });
  78921. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  78922. get: function () {
  78923. return this._boundingBoxSize;
  78924. },
  78925. /**
  78926. * Gets or sets the size of the bounding box associated with the cube texture
  78927. * When defined, the cubemap will switch to local mode
  78928. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  78929. * @example https://www.babylonjs-playground.com/#RNASML
  78930. */
  78931. set: function (value) {
  78932. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  78933. return;
  78934. }
  78935. this._boundingBoxSize = value;
  78936. var scene = this.getScene();
  78937. if (scene) {
  78938. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  78939. }
  78940. },
  78941. enumerable: true,
  78942. configurable: true
  78943. });
  78944. /**
  78945. * Occurs when the file is a preprocessed .babylon.hdr file.
  78946. */
  78947. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  78948. var _this = this;
  78949. var mipLevels = 0;
  78950. var floatArrayView = null;
  78951. var scene = this.getScene();
  78952. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  78953. var mips = new Array();
  78954. if (!floatArrayView) {
  78955. return mips;
  78956. }
  78957. var startIndex = 30;
  78958. for (var level = 0; level < mipLevels; level++) {
  78959. mips.push([]);
  78960. // Fill each pixel of the mip level.
  78961. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  78962. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78963. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  78964. mips[level].push(faceData);
  78965. startIndex += faceSize;
  78966. }
  78967. }
  78968. return mips;
  78969. } : null;
  78970. var callback = function (buffer) {
  78971. var scene = _this.getScene();
  78972. if (!scene) {
  78973. return null;
  78974. }
  78975. // Create Native Array Views
  78976. var intArrayView = new Int32Array(buffer);
  78977. floatArrayView = new Float32Array(buffer);
  78978. // Fill header.
  78979. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  78980. _this._size = intArrayView[1]; // CubeMap max mip face size.
  78981. // Update Texture Information.
  78982. if (!_this._texture) {
  78983. return null;
  78984. }
  78985. _this._texture.updateSize(_this._size, _this._size);
  78986. // Fill polynomial information.
  78987. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  78988. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  78989. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  78990. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  78991. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  78992. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  78993. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  78994. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  78995. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  78996. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  78997. _this.sphericalPolynomial = sphericalPolynomial;
  78998. // Fill pixel data.
  78999. mipLevels = intArrayView[29]; // Number of mip levels.
  79000. var startIndex = 30;
  79001. var data = [];
  79002. var faceSize = Math.pow(_this._size, 2) * 3;
  79003. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79004. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  79005. startIndex += faceSize;
  79006. }
  79007. var results = [];
  79008. var byteArray = null;
  79009. // Push each faces.
  79010. for (var k = 0; k < 6; k++) {
  79011. var dataFace = null;
  79012. // To be deprecated.
  79013. if (version === 1) {
  79014. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  79015. dataFace = data[j];
  79016. }
  79017. // If special cases.
  79018. if (!mipmapGenerator && dataFace) {
  79019. if (!scene.getEngine().getCaps().textureFloat) {
  79020. // 3 channels of 1 bytes per pixel in bytes.
  79021. var byteBuffer = new ArrayBuffer(faceSize);
  79022. byteArray = new Uint8Array(byteBuffer);
  79023. }
  79024. for (var i = 0; i < _this._size * _this._size; i++) {
  79025. // Put in gamma space if requested.
  79026. if (_this._useInGammaSpace) {
  79027. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79028. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79029. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79030. }
  79031. // Convert to int texture for fallback.
  79032. if (byteArray) {
  79033. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79034. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79035. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79036. // May use luminance instead if the result is not accurate.
  79037. var max = Math.max(Math.max(r, g), b);
  79038. if (max > 255) {
  79039. var scale = 255 / max;
  79040. r *= scale;
  79041. g *= scale;
  79042. b *= scale;
  79043. }
  79044. byteArray[(i * 3) + 0] = r;
  79045. byteArray[(i * 3) + 1] = g;
  79046. byteArray[(i * 3) + 2] = b;
  79047. }
  79048. }
  79049. }
  79050. // Fill the array accordingly.
  79051. if (byteArray) {
  79052. results.push(byteArray);
  79053. }
  79054. else {
  79055. results.push(dataFace);
  79056. }
  79057. }
  79058. return results;
  79059. };
  79060. if (scene) {
  79061. 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);
  79062. }
  79063. };
  79064. /**
  79065. * Occurs when the file is raw .hdr file.
  79066. */
  79067. HDRCubeTexture.prototype.loadHDRTexture = function () {
  79068. var _this = this;
  79069. var callback = function (buffer) {
  79070. var scene = _this.getScene();
  79071. if (!scene) {
  79072. return null;
  79073. }
  79074. // Extract the raw linear data.
  79075. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  79076. // Generate harmonics if needed.
  79077. if (_this._generateHarmonics) {
  79078. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  79079. _this.sphericalPolynomial = sphericalPolynomial;
  79080. }
  79081. var results = [];
  79082. var byteArray = null;
  79083. // Push each faces.
  79084. for (var j = 0; j < 6; j++) {
  79085. // Create uintarray fallback.
  79086. if (!scene.getEngine().getCaps().textureFloat) {
  79087. // 3 channels of 1 bytes per pixel in bytes.
  79088. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  79089. byteArray = new Uint8Array(byteBuffer);
  79090. }
  79091. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  79092. // If special cases.
  79093. if (_this._useInGammaSpace || byteArray) {
  79094. for (var i = 0; i < _this._size * _this._size; i++) {
  79095. // Put in gamma space if requested.
  79096. if (_this._useInGammaSpace) {
  79097. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79098. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79099. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79100. }
  79101. // Convert to int texture for fallback.
  79102. if (byteArray) {
  79103. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79104. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79105. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79106. // May use luminance instead if the result is not accurate.
  79107. var max = Math.max(Math.max(r, g), b);
  79108. if (max > 255) {
  79109. var scale = 255 / max;
  79110. r *= scale;
  79111. g *= scale;
  79112. b *= scale;
  79113. }
  79114. byteArray[(i * 3) + 0] = r;
  79115. byteArray[(i * 3) + 1] = g;
  79116. byteArray[(i * 3) + 2] = b;
  79117. }
  79118. }
  79119. }
  79120. if (byteArray) {
  79121. results.push(byteArray);
  79122. }
  79123. else {
  79124. results.push(dataFace);
  79125. }
  79126. }
  79127. return results;
  79128. };
  79129. var mipmapGenerator = null;
  79130. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  79131. // if (!this._noMipmap &&
  79132. // this._usePMREMGenerator) {
  79133. // mipmapGenerator = (data: ArrayBufferView[]) => {
  79134. // // Custom setup of the generator matching with the PBR shader values.
  79135. // var generator = new BABYLON.PMREMGenerator(data,
  79136. // this._size,
  79137. // this._size,
  79138. // 0,
  79139. // 3,
  79140. // this.getScene().getEngine().getCaps().textureFloat,
  79141. // 2048,
  79142. // 0.25,
  79143. // false,
  79144. // true);
  79145. // return generator.filterCubeMap();
  79146. // };
  79147. // }
  79148. var scene = this.getScene();
  79149. if (scene) {
  79150. 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);
  79151. }
  79152. };
  79153. /**
  79154. * Starts the loading process of the texture.
  79155. */
  79156. HDRCubeTexture.prototype.loadTexture = function () {
  79157. if (this._isBABYLONPreprocessed) {
  79158. this.loadBabylonTexture();
  79159. }
  79160. else {
  79161. this.loadHDRTexture();
  79162. }
  79163. };
  79164. HDRCubeTexture.prototype.clone = function () {
  79165. var scene = this.getScene();
  79166. if (!scene) {
  79167. return this;
  79168. }
  79169. var size = (this._isBABYLONPreprocessed ? null : this._size);
  79170. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  79171. // Base texture
  79172. newTexture.level = this.level;
  79173. newTexture.wrapU = this.wrapU;
  79174. newTexture.wrapV = this.wrapV;
  79175. newTexture.coordinatesIndex = this.coordinatesIndex;
  79176. newTexture.coordinatesMode = this.coordinatesMode;
  79177. return newTexture;
  79178. };
  79179. // Methods
  79180. HDRCubeTexture.prototype.delayLoad = function () {
  79181. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79182. return;
  79183. }
  79184. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79185. this._texture = this._getFromCache(this.url, this._noMipmap);
  79186. if (!this._texture) {
  79187. this.loadTexture();
  79188. }
  79189. };
  79190. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  79191. return this._textureMatrix;
  79192. };
  79193. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  79194. this._textureMatrix = value;
  79195. };
  79196. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79197. var texture = null;
  79198. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79199. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  79200. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  79201. texture.name = parsedTexture.name;
  79202. texture.hasAlpha = parsedTexture.hasAlpha;
  79203. texture.level = parsedTexture.level;
  79204. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79205. texture.isBlocking = parsedTexture.isBlocking;
  79206. }
  79207. if (texture) {
  79208. if (parsedTexture.boundingBoxPosition) {
  79209. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79210. }
  79211. if (parsedTexture.boundingBoxSize) {
  79212. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79213. }
  79214. if (parsedTexture.rotationY) {
  79215. texture.rotationY = parsedTexture.rotationY;
  79216. }
  79217. }
  79218. return texture;
  79219. };
  79220. HDRCubeTexture.prototype.serialize = function () {
  79221. if (!this.name) {
  79222. return null;
  79223. }
  79224. var serializationObject = {};
  79225. serializationObject.name = this.name;
  79226. serializationObject.hasAlpha = this.hasAlpha;
  79227. serializationObject.isCube = true;
  79228. serializationObject.level = this.level;
  79229. serializationObject.size = this._size;
  79230. serializationObject.coordinatesMode = this.coordinatesMode;
  79231. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79232. serializationObject.generateHarmonics = this._generateHarmonics;
  79233. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79234. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79235. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79236. serializationObject.noMipmap = this._noMipmap;
  79237. serializationObject.isBlocking = this._isBlocking;
  79238. serializationObject.rotationY = this._rotationY;
  79239. return serializationObject;
  79240. };
  79241. /**
  79242. * Saves as a file the data contained in the texture in a binary format.
  79243. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79244. * as the spherical used in the lighting.
  79245. * @param url The HDR file url.
  79246. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79247. * @param onError Method called if any error happens during download.
  79248. * @return The packed binary data.
  79249. */
  79250. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79251. if (onError === void 0) { onError = null; }
  79252. var callback = function (buffer) {
  79253. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79254. // Returns a URL you can use as a href.
  79255. var objUrl = window.URL.createObjectURL(data);
  79256. // Simulates a link to it and click to dowload.
  79257. var a = document.createElement("a");
  79258. document.body.appendChild(a);
  79259. a.style.display = "none";
  79260. a.href = objUrl;
  79261. a.download = "envmap.babylon.hdr";
  79262. a.click();
  79263. };
  79264. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  79265. };
  79266. /**
  79267. * Serializes the data contained in the texture in a binary format.
  79268. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79269. * as the spherical used in the lighting.
  79270. * @param url The HDR file url.
  79271. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79272. * @param onError Method called if any error happens during download.
  79273. * @return The packed binary data.
  79274. */
  79275. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  79276. if (onError === void 0) { onError = null; }
  79277. // Needs the url tho create the texture.
  79278. if (!url) {
  79279. return;
  79280. }
  79281. // Check Power of two size.
  79282. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  79283. return;
  79284. }
  79285. // Coming Back in 3.x.
  79286. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  79287. };
  79288. HDRCubeTexture._facesMapping = [
  79289. "right",
  79290. "left",
  79291. "up",
  79292. "down",
  79293. "front",
  79294. "back"
  79295. ];
  79296. return HDRCubeTexture;
  79297. }(BABYLON.BaseTexture));
  79298. BABYLON.HDRCubeTexture = HDRCubeTexture;
  79299. })(BABYLON || (BABYLON = {}));
  79300. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  79301. "use strict";
  79302. var BABYLON;
  79303. (function (BABYLON) {
  79304. var IndexedVector2 = /** @class */ (function (_super) {
  79305. __extends(IndexedVector2, _super);
  79306. function IndexedVector2(original, index) {
  79307. var _this = _super.call(this, original.x, original.y) || this;
  79308. _this.index = index;
  79309. return _this;
  79310. }
  79311. return IndexedVector2;
  79312. }(BABYLON.Vector2));
  79313. var PolygonPoints = /** @class */ (function () {
  79314. function PolygonPoints() {
  79315. this.elements = new Array();
  79316. }
  79317. PolygonPoints.prototype.add = function (originalPoints) {
  79318. var _this = this;
  79319. var result = new Array();
  79320. originalPoints.forEach(function (point) {
  79321. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  79322. var newPoint = new IndexedVector2(point, _this.elements.length);
  79323. result.push(newPoint);
  79324. _this.elements.push(newPoint);
  79325. }
  79326. });
  79327. return result;
  79328. };
  79329. PolygonPoints.prototype.computeBounds = function () {
  79330. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79331. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79332. this.elements.forEach(function (point) {
  79333. // x
  79334. if (point.x < lmin.x) {
  79335. lmin.x = point.x;
  79336. }
  79337. else if (point.x > lmax.x) {
  79338. lmax.x = point.x;
  79339. }
  79340. // y
  79341. if (point.y < lmin.y) {
  79342. lmin.y = point.y;
  79343. }
  79344. else if (point.y > lmax.y) {
  79345. lmax.y = point.y;
  79346. }
  79347. });
  79348. return {
  79349. min: lmin,
  79350. max: lmax,
  79351. width: lmax.x - lmin.x,
  79352. height: lmax.y - lmin.y
  79353. };
  79354. };
  79355. return PolygonPoints;
  79356. }());
  79357. var Polygon = /** @class */ (function () {
  79358. function Polygon() {
  79359. }
  79360. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  79361. return [
  79362. new BABYLON.Vector2(xmin, ymin),
  79363. new BABYLON.Vector2(xmax, ymin),
  79364. new BABYLON.Vector2(xmax, ymax),
  79365. new BABYLON.Vector2(xmin, ymax)
  79366. ];
  79367. };
  79368. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  79369. if (cx === void 0) { cx = 0; }
  79370. if (cy === void 0) { cy = 0; }
  79371. if (numberOfSides === void 0) { numberOfSides = 32; }
  79372. var result = new Array();
  79373. var angle = 0;
  79374. var increment = (Math.PI * 2) / numberOfSides;
  79375. for (var i = 0; i < numberOfSides; i++) {
  79376. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  79377. angle -= increment;
  79378. }
  79379. return result;
  79380. };
  79381. Polygon.Parse = function (input) {
  79382. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  79383. var i, result = [];
  79384. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  79385. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  79386. }
  79387. return result;
  79388. };
  79389. Polygon.StartingAt = function (x, y) {
  79390. return BABYLON.Path2.StartingAt(x, y);
  79391. };
  79392. return Polygon;
  79393. }());
  79394. BABYLON.Polygon = Polygon;
  79395. var PolygonMeshBuilder = /** @class */ (function () {
  79396. function PolygonMeshBuilder(name, contours, scene) {
  79397. this._points = new PolygonPoints();
  79398. this._outlinepoints = new PolygonPoints();
  79399. this._holes = new Array();
  79400. this._epoints = new Array();
  79401. this._eholes = new Array();
  79402. this._name = name;
  79403. this._scene = scene;
  79404. var points;
  79405. if (contours instanceof BABYLON.Path2) {
  79406. points = contours.getPoints();
  79407. }
  79408. else {
  79409. points = contours;
  79410. }
  79411. this._addToepoint(points);
  79412. this._points.add(points);
  79413. this._outlinepoints.add(points);
  79414. if (typeof earcut === 'undefined') {
  79415. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  79416. }
  79417. }
  79418. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  79419. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  79420. var p = points_1[_i];
  79421. this._epoints.push(p.x, p.y);
  79422. }
  79423. };
  79424. PolygonMeshBuilder.prototype.addHole = function (hole) {
  79425. this._points.add(hole);
  79426. var holepoints = new PolygonPoints();
  79427. holepoints.add(hole);
  79428. this._holes.push(holepoints);
  79429. this._eholes.push(this._epoints.length / 2);
  79430. this._addToepoint(hole);
  79431. return this;
  79432. };
  79433. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  79434. var _this = this;
  79435. if (updatable === void 0) { updatable = false; }
  79436. if (depth === void 0) { depth = 0; }
  79437. var result = new BABYLON.Mesh(this._name, this._scene);
  79438. var normals = new Array();
  79439. var positions = new Array();
  79440. var uvs = new Array();
  79441. var bounds = this._points.computeBounds();
  79442. this._points.elements.forEach(function (p) {
  79443. normals.push(0, 1.0, 0);
  79444. positions.push(p.x, 0, p.y);
  79445. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  79446. });
  79447. var indices = new Array();
  79448. var res = earcut(this._epoints, this._eholes, 2);
  79449. for (var i = 0; i < res.length; i++) {
  79450. indices.push(res[i]);
  79451. }
  79452. if (depth > 0) {
  79453. var positionscount = (positions.length / 3); //get the current pointcount
  79454. this._points.elements.forEach(function (p) {
  79455. normals.push(0, -1.0, 0);
  79456. positions.push(p.x, -depth, p.y);
  79457. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  79458. });
  79459. var totalCount = indices.length;
  79460. for (var i = 0; i < totalCount; i += 3) {
  79461. var i0 = indices[i + 0];
  79462. var i1 = indices[i + 1];
  79463. var i2 = indices[i + 2];
  79464. indices.push(i2 + positionscount);
  79465. indices.push(i1 + positionscount);
  79466. indices.push(i0 + positionscount);
  79467. }
  79468. //Add the sides
  79469. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  79470. this._holes.forEach(function (hole) {
  79471. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  79472. });
  79473. }
  79474. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  79475. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  79476. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  79477. result.setIndices(indices);
  79478. return result;
  79479. };
  79480. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  79481. var StartIndex = positions.length / 3;
  79482. var ulength = 0;
  79483. for (var i = 0; i < points.elements.length; i++) {
  79484. var p = points.elements[i];
  79485. var p1;
  79486. if ((i + 1) > points.elements.length - 1) {
  79487. p1 = points.elements[0];
  79488. }
  79489. else {
  79490. p1 = points.elements[i + 1];
  79491. }
  79492. positions.push(p.x, 0, p.y);
  79493. positions.push(p.x, -depth, p.y);
  79494. positions.push(p1.x, 0, p1.y);
  79495. positions.push(p1.x, -depth, p1.y);
  79496. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  79497. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  79498. var v3 = v2.subtract(v1);
  79499. var v4 = new BABYLON.Vector3(0, 1, 0);
  79500. var vn = BABYLON.Vector3.Cross(v3, v4);
  79501. vn = vn.normalize();
  79502. uvs.push(ulength / bounds.width, 0);
  79503. uvs.push(ulength / bounds.width, 1);
  79504. ulength += v3.length();
  79505. uvs.push((ulength / bounds.width), 0);
  79506. uvs.push((ulength / bounds.width), 1);
  79507. if (!flip) {
  79508. normals.push(-vn.x, -vn.y, -vn.z);
  79509. normals.push(-vn.x, -vn.y, -vn.z);
  79510. normals.push(-vn.x, -vn.y, -vn.z);
  79511. normals.push(-vn.x, -vn.y, -vn.z);
  79512. indices.push(StartIndex);
  79513. indices.push(StartIndex + 1);
  79514. indices.push(StartIndex + 2);
  79515. indices.push(StartIndex + 1);
  79516. indices.push(StartIndex + 3);
  79517. indices.push(StartIndex + 2);
  79518. }
  79519. else {
  79520. normals.push(vn.x, vn.y, vn.z);
  79521. normals.push(vn.x, vn.y, vn.z);
  79522. normals.push(vn.x, vn.y, vn.z);
  79523. normals.push(vn.x, vn.y, vn.z);
  79524. indices.push(StartIndex);
  79525. indices.push(StartIndex + 2);
  79526. indices.push(StartIndex + 1);
  79527. indices.push(StartIndex + 1);
  79528. indices.push(StartIndex + 2);
  79529. indices.push(StartIndex + 3);
  79530. }
  79531. StartIndex += 4;
  79532. }
  79533. ;
  79534. };
  79535. return PolygonMeshBuilder;
  79536. }());
  79537. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  79538. })(BABYLON || (BABYLON = {}));
  79539. //# sourceMappingURL=babylon.polygonMesh.js.map
  79540. "use strict";
  79541. var BABYLON;
  79542. (function (BABYLON) {
  79543. // Unique ID when we import meshes from Babylon to CSG
  79544. var currentCSGMeshId = 0;
  79545. // # class Vertex
  79546. // Represents a vertex of a polygon. Use your own vertex class instead of this
  79547. // one to provide additional features like texture coordinates and vertex
  79548. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  79549. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  79550. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  79551. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  79552. // is not used anywhere else.
  79553. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  79554. var Vertex = /** @class */ (function () {
  79555. function Vertex(pos, normal, uv) {
  79556. this.pos = pos;
  79557. this.normal = normal;
  79558. this.uv = uv;
  79559. }
  79560. Vertex.prototype.clone = function () {
  79561. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  79562. };
  79563. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  79564. // orientation of a polygon is flipped.
  79565. Vertex.prototype.flip = function () {
  79566. this.normal = this.normal.scale(-1);
  79567. };
  79568. // Create a new vertex between this vertex and `other` by linearly
  79569. // interpolating all properties using a parameter of `t`. Subclasses should
  79570. // override this to interpolate additional properties.
  79571. Vertex.prototype.interpolate = function (other, t) {
  79572. 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));
  79573. };
  79574. return Vertex;
  79575. }());
  79576. // # class Plane
  79577. // Represents a plane in 3D space.
  79578. var Plane = /** @class */ (function () {
  79579. function Plane(normal, w) {
  79580. this.normal = normal;
  79581. this.w = w;
  79582. }
  79583. Plane.FromPoints = function (a, b, c) {
  79584. var v0 = c.subtract(a);
  79585. var v1 = b.subtract(a);
  79586. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  79587. return null;
  79588. }
  79589. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  79590. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  79591. };
  79592. Plane.prototype.clone = function () {
  79593. return new Plane(this.normal.clone(), this.w);
  79594. };
  79595. Plane.prototype.flip = function () {
  79596. this.normal.scaleInPlace(-1);
  79597. this.w = -this.w;
  79598. };
  79599. // Split `polygon` by this plane if needed, then put the polygon or polygon
  79600. // fragments in the appropriate lists. Coplanar polygons go into either
  79601. // `coplanarFront` or `coplanarBack` depending on their orientation with
  79602. // respect to this plane. Polygons in front or in back of this plane go into
  79603. // either `front` or `back`.
  79604. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  79605. var COPLANAR = 0;
  79606. var FRONT = 1;
  79607. var BACK = 2;
  79608. var SPANNING = 3;
  79609. // Classify each point as well as the entire polygon into one of the above
  79610. // four classes.
  79611. var polygonType = 0;
  79612. var types = [];
  79613. var i;
  79614. var t;
  79615. for (i = 0; i < polygon.vertices.length; i++) {
  79616. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  79617. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  79618. polygonType |= type;
  79619. types.push(type);
  79620. }
  79621. // Put the polygon in the correct list, splitting it when necessary.
  79622. switch (polygonType) {
  79623. case COPLANAR:
  79624. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  79625. break;
  79626. case FRONT:
  79627. front.push(polygon);
  79628. break;
  79629. case BACK:
  79630. back.push(polygon);
  79631. break;
  79632. case SPANNING:
  79633. var f = [], b = [];
  79634. for (i = 0; i < polygon.vertices.length; i++) {
  79635. var j = (i + 1) % polygon.vertices.length;
  79636. var ti = types[i], tj = types[j];
  79637. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  79638. if (ti !== BACK)
  79639. f.push(vi);
  79640. if (ti !== FRONT)
  79641. b.push(ti !== BACK ? vi.clone() : vi);
  79642. if ((ti | tj) === SPANNING) {
  79643. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  79644. var v = vi.interpolate(vj, t);
  79645. f.push(v);
  79646. b.push(v.clone());
  79647. }
  79648. }
  79649. var poly;
  79650. if (f.length >= 3) {
  79651. poly = new Polygon(f, polygon.shared);
  79652. if (poly.plane)
  79653. front.push(poly);
  79654. }
  79655. if (b.length >= 3) {
  79656. poly = new Polygon(b, polygon.shared);
  79657. if (poly.plane)
  79658. back.push(poly);
  79659. }
  79660. break;
  79661. }
  79662. };
  79663. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  79664. // point is on the plane.
  79665. Plane.EPSILON = 1e-5;
  79666. return Plane;
  79667. }());
  79668. // # class Polygon
  79669. // Represents a convex polygon. The vertices used to initialize a polygon must
  79670. // be coplanar and form a convex loop.
  79671. //
  79672. // Each convex polygon has a `shared` property, which is shared between all
  79673. // polygons that are clones of each other or were split from the same polygon.
  79674. // This can be used to define per-polygon properties (such as surface color).
  79675. var Polygon = /** @class */ (function () {
  79676. function Polygon(vertices, shared) {
  79677. this.vertices = vertices;
  79678. this.shared = shared;
  79679. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  79680. }
  79681. Polygon.prototype.clone = function () {
  79682. var vertices = this.vertices.map(function (v) { return v.clone(); });
  79683. return new Polygon(vertices, this.shared);
  79684. };
  79685. Polygon.prototype.flip = function () {
  79686. this.vertices.reverse().map(function (v) { v.flip(); });
  79687. this.plane.flip();
  79688. };
  79689. return Polygon;
  79690. }());
  79691. // # class Node
  79692. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  79693. // by picking a polygon to split along. That polygon (and all other coplanar
  79694. // polygons) are added directly to that node and the other polygons are added to
  79695. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  79696. // no distinction between internal and leaf nodes.
  79697. var Node = /** @class */ (function () {
  79698. function Node(polygons) {
  79699. this.plane = null;
  79700. this.front = null;
  79701. this.back = null;
  79702. this.polygons = new Array();
  79703. if (polygons) {
  79704. this.build(polygons);
  79705. }
  79706. }
  79707. Node.prototype.clone = function () {
  79708. var node = new Node();
  79709. node.plane = this.plane && this.plane.clone();
  79710. node.front = this.front && this.front.clone();
  79711. node.back = this.back && this.back.clone();
  79712. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  79713. return node;
  79714. };
  79715. // Convert solid space to empty space and empty space to solid space.
  79716. Node.prototype.invert = function () {
  79717. for (var i = 0; i < this.polygons.length; i++) {
  79718. this.polygons[i].flip();
  79719. }
  79720. if (this.plane) {
  79721. this.plane.flip();
  79722. }
  79723. if (this.front) {
  79724. this.front.invert();
  79725. }
  79726. if (this.back) {
  79727. this.back.invert();
  79728. }
  79729. var temp = this.front;
  79730. this.front = this.back;
  79731. this.back = temp;
  79732. };
  79733. // Recursively remove all polygons in `polygons` that are inside this BSP
  79734. // tree.
  79735. Node.prototype.clipPolygons = function (polygons) {
  79736. if (!this.plane)
  79737. return polygons.slice();
  79738. var front = new Array(), back = new Array();
  79739. for (var i = 0; i < polygons.length; i++) {
  79740. this.plane.splitPolygon(polygons[i], front, back, front, back);
  79741. }
  79742. if (this.front) {
  79743. front = this.front.clipPolygons(front);
  79744. }
  79745. if (this.back) {
  79746. back = this.back.clipPolygons(back);
  79747. }
  79748. else {
  79749. back = [];
  79750. }
  79751. return front.concat(back);
  79752. };
  79753. // Remove all polygons in this BSP tree that are inside the other BSP tree
  79754. // `bsp`.
  79755. Node.prototype.clipTo = function (bsp) {
  79756. this.polygons = bsp.clipPolygons(this.polygons);
  79757. if (this.front)
  79758. this.front.clipTo(bsp);
  79759. if (this.back)
  79760. this.back.clipTo(bsp);
  79761. };
  79762. // Return a list of all polygons in this BSP tree.
  79763. Node.prototype.allPolygons = function () {
  79764. var polygons = this.polygons.slice();
  79765. if (this.front)
  79766. polygons = polygons.concat(this.front.allPolygons());
  79767. if (this.back)
  79768. polygons = polygons.concat(this.back.allPolygons());
  79769. return polygons;
  79770. };
  79771. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  79772. // new polygons are filtered down to the bottom of the tree and become new
  79773. // nodes there. Each set of polygons is partitioned using the first polygon
  79774. // (no heuristic is used to pick a good split).
  79775. Node.prototype.build = function (polygons) {
  79776. if (!polygons.length)
  79777. return;
  79778. if (!this.plane)
  79779. this.plane = polygons[0].plane.clone();
  79780. var front = new Array(), back = new Array();
  79781. for (var i = 0; i < polygons.length; i++) {
  79782. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  79783. }
  79784. if (front.length) {
  79785. if (!this.front)
  79786. this.front = new Node();
  79787. this.front.build(front);
  79788. }
  79789. if (back.length) {
  79790. if (!this.back)
  79791. this.back = new Node();
  79792. this.back.build(back);
  79793. }
  79794. };
  79795. return Node;
  79796. }());
  79797. var CSG = /** @class */ (function () {
  79798. function CSG() {
  79799. this.polygons = new Array();
  79800. }
  79801. // Convert BABYLON.Mesh to BABYLON.CSG
  79802. CSG.FromMesh = function (mesh) {
  79803. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  79804. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  79805. if (mesh instanceof BABYLON.Mesh) {
  79806. mesh.computeWorldMatrix(true);
  79807. matrix = mesh.getWorldMatrix();
  79808. meshPosition = mesh.position.clone();
  79809. meshRotation = mesh.rotation.clone();
  79810. if (mesh.rotationQuaternion) {
  79811. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  79812. }
  79813. meshScaling = mesh.scaling.clone();
  79814. }
  79815. else {
  79816. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  79817. }
  79818. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  79819. var subMeshes = mesh.subMeshes;
  79820. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  79821. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  79822. vertices = [];
  79823. for (var j = 0; j < 3; j++) {
  79824. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  79825. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  79826. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  79827. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  79828. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  79829. vertex = new Vertex(position, normal, uv);
  79830. vertices.push(vertex);
  79831. }
  79832. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  79833. // To handle the case of degenerated triangle
  79834. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  79835. if (polygon.plane)
  79836. polygons.push(polygon);
  79837. }
  79838. }
  79839. var csg = CSG.FromPolygons(polygons);
  79840. csg.matrix = matrix;
  79841. csg.position = meshPosition;
  79842. csg.rotation = meshRotation;
  79843. csg.scaling = meshScaling;
  79844. csg.rotationQuaternion = meshRotationQuaternion;
  79845. currentCSGMeshId++;
  79846. return csg;
  79847. };
  79848. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  79849. CSG.FromPolygons = function (polygons) {
  79850. var csg = new CSG();
  79851. csg.polygons = polygons;
  79852. return csg;
  79853. };
  79854. CSG.prototype.clone = function () {
  79855. var csg = new CSG();
  79856. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  79857. csg.copyTransformAttributes(this);
  79858. return csg;
  79859. };
  79860. CSG.prototype.union = function (csg) {
  79861. var a = new Node(this.clone().polygons);
  79862. var b = new Node(csg.clone().polygons);
  79863. a.clipTo(b);
  79864. b.clipTo(a);
  79865. b.invert();
  79866. b.clipTo(a);
  79867. b.invert();
  79868. a.build(b.allPolygons());
  79869. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79870. };
  79871. CSG.prototype.unionInPlace = function (csg) {
  79872. var a = new Node(this.polygons);
  79873. var b = new Node(csg.polygons);
  79874. a.clipTo(b);
  79875. b.clipTo(a);
  79876. b.invert();
  79877. b.clipTo(a);
  79878. b.invert();
  79879. a.build(b.allPolygons());
  79880. this.polygons = a.allPolygons();
  79881. };
  79882. CSG.prototype.subtract = function (csg) {
  79883. var a = new Node(this.clone().polygons);
  79884. var b = new Node(csg.clone().polygons);
  79885. a.invert();
  79886. a.clipTo(b);
  79887. b.clipTo(a);
  79888. b.invert();
  79889. b.clipTo(a);
  79890. b.invert();
  79891. a.build(b.allPolygons());
  79892. a.invert();
  79893. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79894. };
  79895. CSG.prototype.subtractInPlace = function (csg) {
  79896. var a = new Node(this.polygons);
  79897. var b = new Node(csg.polygons);
  79898. a.invert();
  79899. a.clipTo(b);
  79900. b.clipTo(a);
  79901. b.invert();
  79902. b.clipTo(a);
  79903. b.invert();
  79904. a.build(b.allPolygons());
  79905. a.invert();
  79906. this.polygons = a.allPolygons();
  79907. };
  79908. CSG.prototype.intersect = function (csg) {
  79909. var a = new Node(this.clone().polygons);
  79910. var b = new Node(csg.clone().polygons);
  79911. a.invert();
  79912. b.clipTo(a);
  79913. b.invert();
  79914. a.clipTo(b);
  79915. b.clipTo(a);
  79916. a.build(b.allPolygons());
  79917. a.invert();
  79918. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79919. };
  79920. CSG.prototype.intersectInPlace = function (csg) {
  79921. var a = new Node(this.polygons);
  79922. var b = new Node(csg.polygons);
  79923. a.invert();
  79924. b.clipTo(a);
  79925. b.invert();
  79926. a.clipTo(b);
  79927. b.clipTo(a);
  79928. a.build(b.allPolygons());
  79929. a.invert();
  79930. this.polygons = a.allPolygons();
  79931. };
  79932. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  79933. // not modified.
  79934. CSG.prototype.inverse = function () {
  79935. var csg = this.clone();
  79936. csg.inverseInPlace();
  79937. return csg;
  79938. };
  79939. CSG.prototype.inverseInPlace = function () {
  79940. this.polygons.map(function (p) { p.flip(); });
  79941. };
  79942. // This is used to keep meshes transformations so they can be restored
  79943. // when we build back a Babylon Mesh
  79944. // NB : All CSG operations are performed in world coordinates
  79945. CSG.prototype.copyTransformAttributes = function (csg) {
  79946. this.matrix = csg.matrix;
  79947. this.position = csg.position;
  79948. this.rotation = csg.rotation;
  79949. this.scaling = csg.scaling;
  79950. this.rotationQuaternion = csg.rotationQuaternion;
  79951. return this;
  79952. };
  79953. // Build Raw mesh from CSG
  79954. // Coordinates here are in world space
  79955. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  79956. var matrix = this.matrix.clone();
  79957. matrix.invert();
  79958. 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;
  79959. if (keepSubMeshes) {
  79960. // Sort Polygons, since subMeshes are indices range
  79961. polygons.sort(function (a, b) {
  79962. if (a.shared.meshId === b.shared.meshId) {
  79963. return a.shared.subMeshId - b.shared.subMeshId;
  79964. }
  79965. else {
  79966. return a.shared.meshId - b.shared.meshId;
  79967. }
  79968. });
  79969. }
  79970. for (var i = 0, il = polygons.length; i < il; i++) {
  79971. polygon = polygons[i];
  79972. // Building SubMeshes
  79973. if (!subMesh_dict[polygon.shared.meshId]) {
  79974. subMesh_dict[polygon.shared.meshId] = {};
  79975. }
  79976. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  79977. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  79978. indexStart: +Infinity,
  79979. indexEnd: -Infinity,
  79980. materialIndex: polygon.shared.materialIndex
  79981. };
  79982. }
  79983. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  79984. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  79985. polygonIndices[0] = 0;
  79986. polygonIndices[1] = j - 1;
  79987. polygonIndices[2] = j;
  79988. for (var k = 0; k < 3; k++) {
  79989. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  79990. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  79991. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  79992. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  79993. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  79994. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  79995. // Check if 2 points can be merged
  79996. if (!(typeof vertex_idx !== 'undefined' &&
  79997. normals[vertex_idx * 3] === localNormal.x &&
  79998. normals[vertex_idx * 3 + 1] === localNormal.y &&
  79999. normals[vertex_idx * 3 + 2] === localNormal.z &&
  80000. uvs[vertex_idx * 2] === uv.x &&
  80001. uvs[vertex_idx * 2 + 1] === uv.y)) {
  80002. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  80003. uvs.push(uv.x, uv.y);
  80004. normals.push(normal.x, normal.y, normal.z);
  80005. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  80006. }
  80007. indices.push(vertex_idx);
  80008. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  80009. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  80010. currentIndex++;
  80011. }
  80012. }
  80013. }
  80014. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  80015. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  80016. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  80017. mesh.setIndices(indices, null);
  80018. if (keepSubMeshes) {
  80019. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  80020. var materialIndexOffset = 0, materialMaxIndex;
  80021. mesh.subMeshes = new Array();
  80022. for (var m in subMesh_dict) {
  80023. materialMaxIndex = -1;
  80024. for (var sm in subMesh_dict[m]) {
  80025. subMesh_obj = subMesh_dict[m][sm];
  80026. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  80027. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  80028. }
  80029. materialIndexOffset += ++materialMaxIndex;
  80030. }
  80031. }
  80032. return mesh;
  80033. };
  80034. // Build Mesh from CSG taking material and transforms into account
  80035. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  80036. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  80037. mesh.material = material;
  80038. mesh.position.copyFrom(this.position);
  80039. mesh.rotation.copyFrom(this.rotation);
  80040. if (this.rotationQuaternion) {
  80041. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  80042. }
  80043. mesh.scaling.copyFrom(this.scaling);
  80044. mesh.computeWorldMatrix(true);
  80045. return mesh;
  80046. };
  80047. return CSG;
  80048. }());
  80049. BABYLON.CSG = CSG;
  80050. })(BABYLON || (BABYLON = {}));
  80051. //# sourceMappingURL=babylon.csg.js.map
  80052. "use strict";
  80053. var BABYLON;
  80054. (function (BABYLON) {
  80055. var LensFlare = /** @class */ (function () {
  80056. function LensFlare(size, position, color, imgUrl, system) {
  80057. this.size = size;
  80058. this.position = position;
  80059. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80060. this.color = color || new BABYLON.Color3(1, 1, 1);
  80061. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  80062. this._system = system;
  80063. system.lensFlares.push(this);
  80064. }
  80065. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  80066. return new LensFlare(size, position, color, imgUrl, system);
  80067. };
  80068. LensFlare.prototype.dispose = function () {
  80069. if (this.texture) {
  80070. this.texture.dispose();
  80071. }
  80072. // Remove from scene
  80073. var index = this._system.lensFlares.indexOf(this);
  80074. this._system.lensFlares.splice(index, 1);
  80075. };
  80076. ;
  80077. return LensFlare;
  80078. }());
  80079. BABYLON.LensFlare = LensFlare;
  80080. })(BABYLON || (BABYLON = {}));
  80081. //# sourceMappingURL=babylon.lensFlare.js.map
  80082. "use strict";
  80083. var BABYLON;
  80084. (function (BABYLON) {
  80085. var LensFlareSystem = /** @class */ (function () {
  80086. function LensFlareSystem(name, emitter, scene) {
  80087. this.name = name;
  80088. this.lensFlares = new Array();
  80089. this.borderLimit = 300;
  80090. this.viewportBorder = 0;
  80091. this.layerMask = 0x0FFFFFFF;
  80092. this._vertexBuffers = {};
  80093. this._isEnabled = true;
  80094. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80095. this._emitter = emitter;
  80096. this.id = name;
  80097. scene.lensFlareSystems.push(this);
  80098. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  80099. var engine = scene.getEngine();
  80100. // VBO
  80101. var vertices = [];
  80102. vertices.push(1, 1);
  80103. vertices.push(-1, 1);
  80104. vertices.push(-1, -1);
  80105. vertices.push(1, -1);
  80106. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80107. // Indices
  80108. var indices = [];
  80109. indices.push(0);
  80110. indices.push(1);
  80111. indices.push(2);
  80112. indices.push(0);
  80113. indices.push(2);
  80114. indices.push(3);
  80115. this._indexBuffer = engine.createIndexBuffer(indices);
  80116. // Effects
  80117. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  80118. }
  80119. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  80120. get: function () {
  80121. return this._isEnabled;
  80122. },
  80123. set: function (value) {
  80124. this._isEnabled = value;
  80125. },
  80126. enumerable: true,
  80127. configurable: true
  80128. });
  80129. LensFlareSystem.prototype.getScene = function () {
  80130. return this._scene;
  80131. };
  80132. LensFlareSystem.prototype.getEmitter = function () {
  80133. return this._emitter;
  80134. };
  80135. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  80136. this._emitter = newEmitter;
  80137. };
  80138. LensFlareSystem.prototype.getEmitterPosition = function () {
  80139. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  80140. };
  80141. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  80142. var position = this.getEmitterPosition();
  80143. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  80144. this._positionX = position.x;
  80145. this._positionY = position.y;
  80146. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  80147. if (this.viewportBorder > 0) {
  80148. globalViewport.x -= this.viewportBorder;
  80149. globalViewport.y -= this.viewportBorder;
  80150. globalViewport.width += this.viewportBorder * 2;
  80151. globalViewport.height += this.viewportBorder * 2;
  80152. position.x += this.viewportBorder;
  80153. position.y += this.viewportBorder;
  80154. this._positionX += this.viewportBorder;
  80155. this._positionY += this.viewportBorder;
  80156. }
  80157. if (position.z > 0) {
  80158. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  80159. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  80160. return true;
  80161. }
  80162. return true;
  80163. }
  80164. return false;
  80165. };
  80166. LensFlareSystem.prototype._isVisible = function () {
  80167. if (!this._isEnabled || !this._scene.activeCamera) {
  80168. return false;
  80169. }
  80170. var emitterPosition = this.getEmitterPosition();
  80171. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  80172. var distance = direction.length();
  80173. direction.normalize();
  80174. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  80175. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  80176. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  80177. };
  80178. LensFlareSystem.prototype.render = function () {
  80179. if (!this._effect.isReady() || !this._scene.activeCamera)
  80180. return false;
  80181. var engine = this._scene.getEngine();
  80182. var viewport = this._scene.activeCamera.viewport;
  80183. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  80184. // Position
  80185. if (!this.computeEffectivePosition(globalViewport)) {
  80186. return false;
  80187. }
  80188. // Visibility
  80189. if (!this._isVisible()) {
  80190. return false;
  80191. }
  80192. // Intensity
  80193. var awayX;
  80194. var awayY;
  80195. if (this._positionX < this.borderLimit + globalViewport.x) {
  80196. awayX = this.borderLimit + globalViewport.x - this._positionX;
  80197. }
  80198. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  80199. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  80200. }
  80201. else {
  80202. awayX = 0;
  80203. }
  80204. if (this._positionY < this.borderLimit + globalViewport.y) {
  80205. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80206. }
  80207. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80208. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80209. }
  80210. else {
  80211. awayY = 0;
  80212. }
  80213. var away = (awayX > awayY) ? awayX : awayY;
  80214. away -= this.viewportBorder;
  80215. if (away > this.borderLimit) {
  80216. away = this.borderLimit;
  80217. }
  80218. var intensity = 1.0 - (away / this.borderLimit);
  80219. if (intensity < 0) {
  80220. return false;
  80221. }
  80222. if (intensity > 1.0) {
  80223. intensity = 1.0;
  80224. }
  80225. if (this.viewportBorder > 0) {
  80226. globalViewport.x += this.viewportBorder;
  80227. globalViewport.y += this.viewportBorder;
  80228. globalViewport.width -= this.viewportBorder * 2;
  80229. globalViewport.height -= this.viewportBorder * 2;
  80230. this._positionX -= this.viewportBorder;
  80231. this._positionY -= this.viewportBorder;
  80232. }
  80233. // Position
  80234. var centerX = globalViewport.x + globalViewport.width / 2;
  80235. var centerY = globalViewport.y + globalViewport.height / 2;
  80236. var distX = centerX - this._positionX;
  80237. var distY = centerY - this._positionY;
  80238. // Effects
  80239. engine.enableEffect(this._effect);
  80240. engine.setState(false);
  80241. engine.setDepthBuffer(false);
  80242. // VBOs
  80243. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80244. // Flares
  80245. for (var index = 0; index < this.lensFlares.length; index++) {
  80246. var flare = this.lensFlares[index];
  80247. engine.setAlphaMode(flare.alphaMode);
  80248. var x = centerX - (distX * flare.position);
  80249. var y = centerY - (distY * flare.position);
  80250. var cw = flare.size;
  80251. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80252. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80253. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80254. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80255. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80256. // Texture
  80257. this._effect.setTexture("textureSampler", flare.texture);
  80258. // Color
  80259. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80260. // Draw order
  80261. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80262. }
  80263. engine.setDepthBuffer(true);
  80264. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80265. return true;
  80266. };
  80267. LensFlareSystem.prototype.dispose = function () {
  80268. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80269. if (vertexBuffer) {
  80270. vertexBuffer.dispose();
  80271. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80272. }
  80273. if (this._indexBuffer) {
  80274. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80275. this._indexBuffer = null;
  80276. }
  80277. while (this.lensFlares.length) {
  80278. this.lensFlares[0].dispose();
  80279. }
  80280. // Remove from scene
  80281. var index = this._scene.lensFlareSystems.indexOf(this);
  80282. this._scene.lensFlareSystems.splice(index, 1);
  80283. };
  80284. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  80285. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  80286. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  80287. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  80288. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  80289. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  80290. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  80291. var parsedFlare = parsedLensFlareSystem.flares[index];
  80292. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  80293. }
  80294. return lensFlareSystem;
  80295. };
  80296. LensFlareSystem.prototype.serialize = function () {
  80297. var serializationObject = {};
  80298. serializationObject.id = this.id;
  80299. serializationObject.name = this.name;
  80300. serializationObject.emitterId = this.getEmitter().id;
  80301. serializationObject.borderLimit = this.borderLimit;
  80302. serializationObject.flares = [];
  80303. for (var index = 0; index < this.lensFlares.length; index++) {
  80304. var flare = this.lensFlares[index];
  80305. serializationObject.flares.push({
  80306. size: flare.size,
  80307. position: flare.position,
  80308. color: flare.color.asArray(),
  80309. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  80310. });
  80311. }
  80312. return serializationObject;
  80313. };
  80314. return LensFlareSystem;
  80315. }());
  80316. BABYLON.LensFlareSystem = LensFlareSystem;
  80317. })(BABYLON || (BABYLON = {}));
  80318. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  80319. "use strict";
  80320. var BABYLON;
  80321. (function (BABYLON) {
  80322. /**
  80323. * This is a holder class for the physics joint created by the physics plugin.
  80324. * It holds a set of functions to control the underlying joint.
  80325. */
  80326. var PhysicsJoint = /** @class */ (function () {
  80327. function PhysicsJoint(type, jointData) {
  80328. this.type = type;
  80329. this.jointData = jointData;
  80330. jointData.nativeParams = jointData.nativeParams || {};
  80331. }
  80332. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  80333. get: function () {
  80334. return this._physicsJoint;
  80335. },
  80336. set: function (newJoint) {
  80337. if (this._physicsJoint) {
  80338. //remove from the wolrd
  80339. }
  80340. this._physicsJoint = newJoint;
  80341. },
  80342. enumerable: true,
  80343. configurable: true
  80344. });
  80345. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  80346. set: function (physicsPlugin) {
  80347. this._physicsPlugin = physicsPlugin;
  80348. },
  80349. enumerable: true,
  80350. configurable: true
  80351. });
  80352. /**
  80353. * Execute a function that is physics-plugin specific.
  80354. * @param {Function} func the function that will be executed.
  80355. * It accepts two parameters: the physics world and the physics joint.
  80356. */
  80357. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  80358. func(this._physicsPlugin.world, this._physicsJoint);
  80359. };
  80360. //TODO check if the native joints are the same
  80361. //Joint Types
  80362. PhysicsJoint.DistanceJoint = 0;
  80363. PhysicsJoint.HingeJoint = 1;
  80364. PhysicsJoint.BallAndSocketJoint = 2;
  80365. PhysicsJoint.WheelJoint = 3;
  80366. PhysicsJoint.SliderJoint = 4;
  80367. //OIMO
  80368. PhysicsJoint.PrismaticJoint = 5;
  80369. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  80370. PhysicsJoint.UniversalJoint = 6;
  80371. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  80372. //Cannon
  80373. //Similar to a Ball-Joint. Different in params
  80374. PhysicsJoint.PointToPointJoint = 8;
  80375. //Cannon only at the moment
  80376. PhysicsJoint.SpringJoint = 9;
  80377. PhysicsJoint.LockJoint = 10;
  80378. return PhysicsJoint;
  80379. }());
  80380. BABYLON.PhysicsJoint = PhysicsJoint;
  80381. /**
  80382. * A class representing a physics distance joint.
  80383. */
  80384. var DistanceJoint = /** @class */ (function (_super) {
  80385. __extends(DistanceJoint, _super);
  80386. function DistanceJoint(jointData) {
  80387. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  80388. }
  80389. /**
  80390. * Update the predefined distance.
  80391. */
  80392. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  80393. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  80394. };
  80395. return DistanceJoint;
  80396. }(PhysicsJoint));
  80397. BABYLON.DistanceJoint = DistanceJoint;
  80398. var MotorEnabledJoint = /** @class */ (function (_super) {
  80399. __extends(MotorEnabledJoint, _super);
  80400. function MotorEnabledJoint(type, jointData) {
  80401. return _super.call(this, type, jointData) || this;
  80402. }
  80403. /**
  80404. * Set the motor values.
  80405. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80406. * @param {number} force the force to apply
  80407. * @param {number} maxForce max force for this motor.
  80408. */
  80409. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  80410. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80411. };
  80412. /**
  80413. * Set the motor's limits.
  80414. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80415. */
  80416. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80417. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80418. };
  80419. return MotorEnabledJoint;
  80420. }(PhysicsJoint));
  80421. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  80422. /**
  80423. * This class represents a single hinge physics joint
  80424. */
  80425. var HingeJoint = /** @class */ (function (_super) {
  80426. __extends(HingeJoint, _super);
  80427. function HingeJoint(jointData) {
  80428. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  80429. }
  80430. /**
  80431. * Set the motor values.
  80432. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80433. * @param {number} force the force to apply
  80434. * @param {number} maxForce max force for this motor.
  80435. */
  80436. HingeJoint.prototype.setMotor = function (force, maxForce) {
  80437. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80438. };
  80439. /**
  80440. * Set the motor's limits.
  80441. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80442. */
  80443. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80444. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80445. };
  80446. return HingeJoint;
  80447. }(MotorEnabledJoint));
  80448. BABYLON.HingeJoint = HingeJoint;
  80449. /**
  80450. * This class represents a dual hinge physics joint (same as wheel joint)
  80451. */
  80452. var Hinge2Joint = /** @class */ (function (_super) {
  80453. __extends(Hinge2Joint, _super);
  80454. function Hinge2Joint(jointData) {
  80455. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  80456. }
  80457. /**
  80458. * Set the motor values.
  80459. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80460. * @param {number} force the force to apply
  80461. * @param {number} maxForce max force for this motor.
  80462. * @param {motorIndex} the motor's index, 0 or 1.
  80463. */
  80464. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  80465. if (motorIndex === void 0) { motorIndex = 0; }
  80466. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  80467. };
  80468. /**
  80469. * Set the motor limits.
  80470. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80471. * @param {number} upperLimit the upper limit
  80472. * @param {number} lowerLimit lower limit
  80473. * @param {motorIndex} the motor's index, 0 or 1.
  80474. */
  80475. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  80476. if (motorIndex === void 0) { motorIndex = 0; }
  80477. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  80478. };
  80479. return Hinge2Joint;
  80480. }(MotorEnabledJoint));
  80481. BABYLON.Hinge2Joint = Hinge2Joint;
  80482. })(BABYLON || (BABYLON = {}));
  80483. //# sourceMappingURL=babylon.physicsJoint.js.map
  80484. "use strict";
  80485. var BABYLON;
  80486. (function (BABYLON) {
  80487. var PhysicsImpostor = /** @class */ (function () {
  80488. function PhysicsImpostor(object, type, _options, _scene) {
  80489. if (_options === void 0) { _options = { mass: 0 }; }
  80490. var _this = this;
  80491. this.object = object;
  80492. this.type = type;
  80493. this._options = _options;
  80494. this._scene = _scene;
  80495. this._bodyUpdateRequired = false;
  80496. this._onBeforePhysicsStepCallbacks = new Array();
  80497. this._onAfterPhysicsStepCallbacks = new Array();
  80498. this._onPhysicsCollideCallbacks = [];
  80499. this._deltaPosition = BABYLON.Vector3.Zero();
  80500. this._isDisposed = false;
  80501. //temp variables for parent rotation calculations
  80502. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  80503. this._tmpQuat = new BABYLON.Quaternion();
  80504. this._tmpQuat2 = new BABYLON.Quaternion();
  80505. /**
  80506. * this function is executed by the physics engine.
  80507. */
  80508. this.beforeStep = function () {
  80509. if (!_this._physicsEngine) {
  80510. return;
  80511. }
  80512. _this.object.translate(_this._deltaPosition, -1);
  80513. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  80514. _this.object.computeWorldMatrix(false);
  80515. if (_this.object.parent && _this.object.rotationQuaternion) {
  80516. _this.getParentsRotation();
  80517. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  80518. }
  80519. else {
  80520. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  80521. }
  80522. if (!_this._options.disableBidirectionalTransformation) {
  80523. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  80524. }
  80525. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  80526. func(_this);
  80527. });
  80528. };
  80529. /**
  80530. * this function is executed by the physics engine.
  80531. */
  80532. this.afterStep = function () {
  80533. if (!_this._physicsEngine) {
  80534. return;
  80535. }
  80536. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  80537. func(_this);
  80538. });
  80539. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  80540. // object has now its world rotation. needs to be converted to local.
  80541. if (_this.object.parent && _this.object.rotationQuaternion) {
  80542. _this.getParentsRotation();
  80543. _this._tmpQuat.conjugateInPlace();
  80544. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  80545. }
  80546. // take the position set and make it the absolute position of this object.
  80547. _this.object.setAbsolutePosition(_this.object.position);
  80548. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  80549. _this.object.translate(_this._deltaPosition, 1);
  80550. };
  80551. /**
  80552. * Legacy collision detection event support
  80553. */
  80554. this.onCollideEvent = null;
  80555. //event and body object due to cannon's event-based architecture.
  80556. this.onCollide = function (e) {
  80557. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  80558. return;
  80559. }
  80560. if (!_this._physicsEngine) {
  80561. return;
  80562. }
  80563. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  80564. if (otherImpostor) {
  80565. // Legacy collision detection event support
  80566. if (_this.onCollideEvent) {
  80567. _this.onCollideEvent(_this, otherImpostor);
  80568. }
  80569. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  80570. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  80571. }).forEach(function (obj) {
  80572. obj.callback(_this, otherImpostor);
  80573. });
  80574. }
  80575. };
  80576. //sanity check!
  80577. if (!this.object) {
  80578. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  80579. return;
  80580. }
  80581. //legacy support for old syntax.
  80582. if (!this._scene && object.getScene) {
  80583. this._scene = object.getScene();
  80584. }
  80585. if (!this._scene) {
  80586. return;
  80587. }
  80588. this._physicsEngine = this._scene.getPhysicsEngine();
  80589. if (!this._physicsEngine) {
  80590. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  80591. }
  80592. else {
  80593. //set the object's quaternion, if not set
  80594. if (!this.object.rotationQuaternion) {
  80595. if (this.object.rotation) {
  80596. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  80597. }
  80598. else {
  80599. this.object.rotationQuaternion = new BABYLON.Quaternion();
  80600. }
  80601. }
  80602. //default options params
  80603. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  80604. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  80605. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  80606. this._joints = [];
  80607. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  80608. if (!this.object.parent || this._options.ignoreParent) {
  80609. this._init();
  80610. }
  80611. else if (this.object.parent.physicsImpostor) {
  80612. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  80613. }
  80614. }
  80615. }
  80616. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  80617. get: function () {
  80618. return this._isDisposed;
  80619. },
  80620. enumerable: true,
  80621. configurable: true
  80622. });
  80623. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  80624. get: function () {
  80625. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  80626. },
  80627. set: function (value) {
  80628. this.setMass(value);
  80629. },
  80630. enumerable: true,
  80631. configurable: true
  80632. });
  80633. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  80634. get: function () {
  80635. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  80636. },
  80637. set: function (value) {
  80638. if (!this._physicsEngine) {
  80639. return;
  80640. }
  80641. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  80642. },
  80643. enumerable: true,
  80644. configurable: true
  80645. });
  80646. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  80647. get: function () {
  80648. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  80649. },
  80650. set: function (value) {
  80651. if (!this._physicsEngine) {
  80652. return;
  80653. }
  80654. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  80655. },
  80656. enumerable: true,
  80657. configurable: true
  80658. });
  80659. /**
  80660. * This function will completly initialize this impostor.
  80661. * It will create a new body - but only if this mesh has no parent.
  80662. * If it has, this impostor will not be used other than to define the impostor
  80663. * of the child mesh.
  80664. */
  80665. PhysicsImpostor.prototype._init = function () {
  80666. if (!this._physicsEngine) {
  80667. return;
  80668. }
  80669. this._physicsEngine.removeImpostor(this);
  80670. this.physicsBody = null;
  80671. this._parent = this._parent || this._getPhysicsParent();
  80672. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  80673. this._physicsEngine.addImpostor(this);
  80674. }
  80675. };
  80676. PhysicsImpostor.prototype._getPhysicsParent = function () {
  80677. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  80678. var parentMesh = this.object.parent;
  80679. return parentMesh.physicsImpostor;
  80680. }
  80681. return null;
  80682. };
  80683. /**
  80684. * Should a new body be generated.
  80685. */
  80686. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  80687. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  80688. };
  80689. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  80690. this.forceUpdate();
  80691. };
  80692. /**
  80693. * Force a regeneration of this or the parent's impostor's body.
  80694. * Use under cautious - This will remove all joints already implemented.
  80695. */
  80696. PhysicsImpostor.prototype.forceUpdate = function () {
  80697. this._init();
  80698. if (this.parent && !this._options.ignoreParent) {
  80699. this.parent.forceUpdate();
  80700. }
  80701. };
  80702. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  80703. /*public get mesh(): AbstractMesh {
  80704. return this._mesh;
  80705. }*/
  80706. /**
  80707. * Gets the body that holds this impostor. Either its own, or its parent.
  80708. */
  80709. get: function () {
  80710. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  80711. },
  80712. /**
  80713. * Set the physics body. Used mainly by the physics engine/plugin
  80714. */
  80715. set: function (physicsBody) {
  80716. if (this._physicsBody && this._physicsEngine) {
  80717. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  80718. }
  80719. this._physicsBody = physicsBody;
  80720. this.resetUpdateFlags();
  80721. },
  80722. enumerable: true,
  80723. configurable: true
  80724. });
  80725. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  80726. get: function () {
  80727. return !this._options.ignoreParent && this._parent ? this._parent : null;
  80728. },
  80729. set: function (value) {
  80730. this._parent = value;
  80731. },
  80732. enumerable: true,
  80733. configurable: true
  80734. });
  80735. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  80736. this._bodyUpdateRequired = false;
  80737. };
  80738. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  80739. if (this.object.getBoundingInfo) {
  80740. var q = this.object.rotationQuaternion;
  80741. //reset rotation
  80742. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  80743. //calculate the world matrix with no rotation
  80744. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80745. var boundingInfo = this.object.getBoundingInfo();
  80746. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  80747. //bring back the rotation
  80748. this.object.rotationQuaternion = q;
  80749. //calculate the world matrix with the new rotation
  80750. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80751. return size;
  80752. }
  80753. else {
  80754. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  80755. }
  80756. };
  80757. PhysicsImpostor.prototype.getObjectCenter = function () {
  80758. if (this.object.getBoundingInfo) {
  80759. var boundingInfo = this.object.getBoundingInfo();
  80760. return boundingInfo.boundingBox.centerWorld;
  80761. }
  80762. else {
  80763. return this.object.position;
  80764. }
  80765. };
  80766. /**
  80767. * Get a specific parametes from the options parameter.
  80768. */
  80769. PhysicsImpostor.prototype.getParam = function (paramName) {
  80770. return this._options[paramName];
  80771. };
  80772. /**
  80773. * Sets a specific parameter in the options given to the physics plugin
  80774. */
  80775. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  80776. this._options[paramName] = value;
  80777. this._bodyUpdateRequired = true;
  80778. };
  80779. /**
  80780. * Specifically change the body's mass option. Won't recreate the physics body object
  80781. */
  80782. PhysicsImpostor.prototype.setMass = function (mass) {
  80783. if (this.getParam("mass") !== mass) {
  80784. this.setParam("mass", mass);
  80785. }
  80786. if (this._physicsEngine) {
  80787. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  80788. }
  80789. };
  80790. PhysicsImpostor.prototype.getLinearVelocity = function () {
  80791. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  80792. };
  80793. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  80794. if (this._physicsEngine) {
  80795. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  80796. }
  80797. };
  80798. PhysicsImpostor.prototype.getAngularVelocity = function () {
  80799. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  80800. };
  80801. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  80802. if (this._physicsEngine) {
  80803. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  80804. }
  80805. };
  80806. /**
  80807. * Execute a function with the physics plugin native code.
  80808. * Provide a function the will have two variables - the world object and the physics body object.
  80809. */
  80810. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  80811. if (this._physicsEngine) {
  80812. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  80813. }
  80814. };
  80815. /**
  80816. * Register a function that will be executed before the physics world is stepping forward.
  80817. */
  80818. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  80819. this._onBeforePhysicsStepCallbacks.push(func);
  80820. };
  80821. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  80822. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  80823. if (index > -1) {
  80824. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  80825. }
  80826. else {
  80827. BABYLON.Tools.Warn("Function to remove was not found");
  80828. }
  80829. };
  80830. /**
  80831. * Register a function that will be executed after the physics step
  80832. */
  80833. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  80834. this._onAfterPhysicsStepCallbacks.push(func);
  80835. };
  80836. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  80837. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  80838. if (index > -1) {
  80839. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  80840. }
  80841. else {
  80842. BABYLON.Tools.Warn("Function to remove was not found");
  80843. }
  80844. };
  80845. /**
  80846. * register a function that will be executed when this impostor collides against a different body.
  80847. */
  80848. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  80849. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80850. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  80851. };
  80852. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  80853. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80854. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  80855. if (index > -1) {
  80856. this._onPhysicsCollideCallbacks.splice(index, 1);
  80857. }
  80858. else {
  80859. BABYLON.Tools.Warn("Function to remove was not found");
  80860. }
  80861. };
  80862. PhysicsImpostor.prototype.getParentsRotation = function () {
  80863. var parent = this.object.parent;
  80864. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  80865. while (parent) {
  80866. if (parent.rotationQuaternion) {
  80867. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  80868. }
  80869. else {
  80870. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  80871. }
  80872. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  80873. parent = parent.parent;
  80874. }
  80875. return this._tmpQuat;
  80876. };
  80877. /**
  80878. * Apply a force
  80879. */
  80880. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  80881. if (this._physicsEngine) {
  80882. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  80883. }
  80884. return this;
  80885. };
  80886. /**
  80887. * Apply an impulse
  80888. */
  80889. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  80890. if (this._physicsEngine) {
  80891. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  80892. }
  80893. return this;
  80894. };
  80895. /**
  80896. * A help function to create a joint.
  80897. */
  80898. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  80899. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  80900. this.addJoint(otherImpostor, joint);
  80901. return this;
  80902. };
  80903. /**
  80904. * Add a joint to this impostor with a different impostor.
  80905. */
  80906. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  80907. this._joints.push({
  80908. otherImpostor: otherImpostor,
  80909. joint: joint
  80910. });
  80911. if (this._physicsEngine) {
  80912. this._physicsEngine.addJoint(this, otherImpostor, joint);
  80913. }
  80914. return this;
  80915. };
  80916. /**
  80917. * Will keep this body still, in a sleep mode.
  80918. */
  80919. PhysicsImpostor.prototype.sleep = function () {
  80920. if (this._physicsEngine) {
  80921. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  80922. }
  80923. return this;
  80924. };
  80925. /**
  80926. * Wake the body up.
  80927. */
  80928. PhysicsImpostor.prototype.wakeUp = function () {
  80929. if (this._physicsEngine) {
  80930. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  80931. }
  80932. return this;
  80933. };
  80934. PhysicsImpostor.prototype.clone = function (newObject) {
  80935. if (!newObject)
  80936. return null;
  80937. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  80938. };
  80939. PhysicsImpostor.prototype.dispose = function () {
  80940. var _this = this;
  80941. //no dispose if no physics engine is available.
  80942. if (!this._physicsEngine) {
  80943. return;
  80944. }
  80945. this._joints.forEach(function (j) {
  80946. if (_this._physicsEngine) {
  80947. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  80948. }
  80949. });
  80950. //dispose the physics body
  80951. this._physicsEngine.removeImpostor(this);
  80952. if (this.parent) {
  80953. this.parent.forceUpdate();
  80954. }
  80955. else {
  80956. /*this._object.getChildMeshes().forEach(function(mesh) {
  80957. if (mesh.physicsImpostor) {
  80958. if (disposeChildren) {
  80959. mesh.physicsImpostor.dispose();
  80960. mesh.physicsImpostor = null;
  80961. }
  80962. }
  80963. })*/
  80964. }
  80965. this._isDisposed = true;
  80966. };
  80967. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  80968. this._deltaPosition.copyFrom(position);
  80969. };
  80970. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  80971. if (!this._deltaRotation) {
  80972. this._deltaRotation = new BABYLON.Quaternion();
  80973. }
  80974. this._deltaRotation.copyFrom(rotation);
  80975. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  80976. };
  80977. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  80978. if (this._physicsEngine) {
  80979. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  80980. }
  80981. return this;
  80982. };
  80983. PhysicsImpostor.prototype.getRadius = function () {
  80984. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  80985. };
  80986. /**
  80987. * Sync a bone with this impostor
  80988. * @param bone The bone to sync to the impostor.
  80989. * @param boneMesh The mesh that the bone is influencing.
  80990. * @param jointPivot The pivot of the joint / bone in local space.
  80991. * @param distToJoint Optional distance from the impostor to the joint.
  80992. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80993. */
  80994. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  80995. var tempVec = PhysicsImpostor._tmpVecs[0];
  80996. var mesh = this.object;
  80997. if (mesh.rotationQuaternion) {
  80998. if (adjustRotation) {
  80999. var tempQuat = PhysicsImpostor._tmpQuat;
  81000. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  81001. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  81002. }
  81003. else {
  81004. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  81005. }
  81006. }
  81007. tempVec.x = 0;
  81008. tempVec.y = 0;
  81009. tempVec.z = 0;
  81010. if (jointPivot) {
  81011. tempVec.x = jointPivot.x;
  81012. tempVec.y = jointPivot.y;
  81013. tempVec.z = jointPivot.z;
  81014. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  81015. if (distToJoint === undefined || distToJoint === null) {
  81016. distToJoint = jointPivot.length();
  81017. }
  81018. tempVec.x *= distToJoint;
  81019. tempVec.y *= distToJoint;
  81020. tempVec.z *= distToJoint;
  81021. }
  81022. if (bone.getParent()) {
  81023. tempVec.addInPlace(mesh.getAbsolutePosition());
  81024. bone.setAbsolutePosition(tempVec, boneMesh);
  81025. }
  81026. else {
  81027. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  81028. boneMesh.position.x -= tempVec.x;
  81029. boneMesh.position.y -= tempVec.y;
  81030. boneMesh.position.z -= tempVec.z;
  81031. }
  81032. };
  81033. /**
  81034. * Sync impostor to a bone
  81035. * @param bone The bone that the impostor will be synced to.
  81036. * @param boneMesh The mesh that the bone is influencing.
  81037. * @param jointPivot The pivot of the joint / bone in local space.
  81038. * @param distToJoint Optional distance from the impostor to the joint.
  81039. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81040. * @param boneAxis Optional vector3 axis the bone is aligned with
  81041. */
  81042. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  81043. var mesh = this.object;
  81044. if (mesh.rotationQuaternion) {
  81045. if (adjustRotation) {
  81046. var tempQuat = PhysicsImpostor._tmpQuat;
  81047. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  81048. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  81049. }
  81050. else {
  81051. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  81052. }
  81053. }
  81054. var pos = PhysicsImpostor._tmpVecs[0];
  81055. var boneDir = PhysicsImpostor._tmpVecs[1];
  81056. if (!boneAxis) {
  81057. boneAxis = PhysicsImpostor._tmpVecs[2];
  81058. boneAxis.x = 0;
  81059. boneAxis.y = 1;
  81060. boneAxis.z = 0;
  81061. }
  81062. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  81063. bone.getAbsolutePositionToRef(boneMesh, pos);
  81064. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  81065. distToJoint = jointPivot.length();
  81066. }
  81067. if (distToJoint !== undefined && distToJoint !== null) {
  81068. pos.x += boneDir.x * distToJoint;
  81069. pos.y += boneDir.y * distToJoint;
  81070. pos.z += boneDir.z * distToJoint;
  81071. }
  81072. mesh.setAbsolutePosition(pos);
  81073. };
  81074. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  81075. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  81076. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81077. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  81078. //Impostor types
  81079. PhysicsImpostor.NoImpostor = 0;
  81080. PhysicsImpostor.SphereImpostor = 1;
  81081. PhysicsImpostor.BoxImpostor = 2;
  81082. PhysicsImpostor.PlaneImpostor = 3;
  81083. PhysicsImpostor.MeshImpostor = 4;
  81084. PhysicsImpostor.CylinderImpostor = 7;
  81085. PhysicsImpostor.ParticleImpostor = 8;
  81086. PhysicsImpostor.HeightmapImpostor = 9;
  81087. return PhysicsImpostor;
  81088. }());
  81089. BABYLON.PhysicsImpostor = PhysicsImpostor;
  81090. })(BABYLON || (BABYLON = {}));
  81091. //# sourceMappingURL=babylon.physicsImpostor.js.map
  81092. "use strict";
  81093. var BABYLON;
  81094. (function (BABYLON) {
  81095. var PhysicsEngine = /** @class */ (function () {
  81096. function PhysicsEngine(gravity, _physicsPlugin) {
  81097. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  81098. this._physicsPlugin = _physicsPlugin;
  81099. //new methods and parameters
  81100. this._impostors = [];
  81101. this._joints = [];
  81102. if (!this._physicsPlugin.isSupported()) {
  81103. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  81104. + "Please make sure it is included.");
  81105. }
  81106. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  81107. this.setGravity(gravity);
  81108. this.setTimeStep();
  81109. }
  81110. PhysicsEngine.prototype.setGravity = function (gravity) {
  81111. this.gravity = gravity;
  81112. this._physicsPlugin.setGravity(this.gravity);
  81113. };
  81114. /**
  81115. * Set the time step of the physics engine.
  81116. * default is 1/60.
  81117. * To slow it down, enter 1/600 for example.
  81118. * To speed it up, 1/30
  81119. * @param {number} newTimeStep the new timestep to apply to this world.
  81120. */
  81121. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  81122. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  81123. this._physicsPlugin.setTimeStep(newTimeStep);
  81124. };
  81125. /**
  81126. * Get the time step of the physics engine.
  81127. */
  81128. PhysicsEngine.prototype.getTimeStep = function () {
  81129. return this._physicsPlugin.getTimeStep();
  81130. };
  81131. PhysicsEngine.prototype.dispose = function () {
  81132. this._impostors.forEach(function (impostor) {
  81133. impostor.dispose();
  81134. });
  81135. this._physicsPlugin.dispose();
  81136. };
  81137. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  81138. return this._physicsPlugin.name;
  81139. };
  81140. /**
  81141. * Adding a new impostor for the impostor tracking.
  81142. * This will be done by the impostor itself.
  81143. * @param {PhysicsImpostor} impostor the impostor to add
  81144. */
  81145. PhysicsEngine.prototype.addImpostor = function (impostor) {
  81146. impostor.uniqueId = this._impostors.push(impostor);
  81147. //if no parent, generate the body
  81148. if (!impostor.parent) {
  81149. this._physicsPlugin.generatePhysicsBody(impostor);
  81150. }
  81151. };
  81152. /**
  81153. * Remove an impostor from the engine.
  81154. * This impostor and its mesh will not longer be updated by the physics engine.
  81155. * @param {PhysicsImpostor} impostor the impostor to remove
  81156. */
  81157. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  81158. var index = this._impostors.indexOf(impostor);
  81159. if (index > -1) {
  81160. var removed = this._impostors.splice(index, 1);
  81161. //Is it needed?
  81162. if (removed.length) {
  81163. //this will also remove it from the world.
  81164. removed[0].physicsBody = null;
  81165. }
  81166. }
  81167. };
  81168. /**
  81169. * Add a joint to the physics engine
  81170. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  81171. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  81172. * @param {PhysicsJoint} the joint that will connect both impostors.
  81173. */
  81174. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  81175. var impostorJoint = {
  81176. mainImpostor: mainImpostor,
  81177. connectedImpostor: connectedImpostor,
  81178. joint: joint
  81179. };
  81180. joint.physicsPlugin = this._physicsPlugin;
  81181. this._joints.push(impostorJoint);
  81182. this._physicsPlugin.generateJoint(impostorJoint);
  81183. };
  81184. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  81185. var matchingJoints = this._joints.filter(function (impostorJoint) {
  81186. return (impostorJoint.connectedImpostor === connectedImpostor
  81187. && impostorJoint.joint === joint
  81188. && impostorJoint.mainImpostor === mainImpostor);
  81189. });
  81190. if (matchingJoints.length) {
  81191. this._physicsPlugin.removeJoint(matchingJoints[0]);
  81192. //TODO remove it from the list as well
  81193. }
  81194. };
  81195. /**
  81196. * Called by the scene. no need to call it.
  81197. */
  81198. PhysicsEngine.prototype._step = function (delta) {
  81199. var _this = this;
  81200. //check if any mesh has no body / requires an update
  81201. this._impostors.forEach(function (impostor) {
  81202. if (impostor.isBodyInitRequired()) {
  81203. _this._physicsPlugin.generatePhysicsBody(impostor);
  81204. }
  81205. });
  81206. if (delta > 0.1) {
  81207. delta = 0.1;
  81208. }
  81209. else if (delta <= 0) {
  81210. delta = 1.0 / 60.0;
  81211. }
  81212. this._physicsPlugin.executeStep(delta, this._impostors);
  81213. };
  81214. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81215. return this._physicsPlugin;
  81216. };
  81217. PhysicsEngine.prototype.getImpostors = function () {
  81218. return this._impostors;
  81219. };
  81220. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81221. for (var i = 0; i < this._impostors.length; ++i) {
  81222. if (this._impostors[i].object === object) {
  81223. return this._impostors[i];
  81224. }
  81225. }
  81226. return null;
  81227. };
  81228. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81229. for (var i = 0; i < this._impostors.length; ++i) {
  81230. if (this._impostors[i].physicsBody === body) {
  81231. return this._impostors[i];
  81232. }
  81233. }
  81234. return null;
  81235. };
  81236. // Statics
  81237. PhysicsEngine.Epsilon = 0.001;
  81238. return PhysicsEngine;
  81239. }());
  81240. BABYLON.PhysicsEngine = PhysicsEngine;
  81241. })(BABYLON || (BABYLON = {}));
  81242. //# sourceMappingURL=babylon.physicsEngine.js.map
  81243. "use strict";
  81244. var BABYLON;
  81245. (function (BABYLON) {
  81246. var PhysicsHelper = /** @class */ (function () {
  81247. function PhysicsHelper(scene) {
  81248. this._scene = scene;
  81249. this._physicsEngine = this._scene.getPhysicsEngine();
  81250. if (!this._physicsEngine) {
  81251. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81252. }
  81253. }
  81254. /**
  81255. * @param {Vector3} origin the origin of the explosion
  81256. * @param {number} radius the explosion radius
  81257. * @param {number} strength the explosion strength
  81258. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81259. */
  81260. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81261. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81262. if (!this._physicsEngine) {
  81263. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81264. return null;
  81265. }
  81266. var impostors = this._physicsEngine.getImpostors();
  81267. if (impostors.length === 0) {
  81268. return null;
  81269. }
  81270. var event = new PhysicsRadialExplosionEvent(this._scene);
  81271. impostors.forEach(function (impostor) {
  81272. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81273. if (!impostorForceAndContactPoint) {
  81274. return;
  81275. }
  81276. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81277. });
  81278. event.dispose(false);
  81279. return event;
  81280. };
  81281. /**
  81282. * @param {Vector3} origin the origin of the explosion
  81283. * @param {number} radius the explosion radius
  81284. * @param {number} strength the explosion strength
  81285. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81286. */
  81287. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  81288. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81289. if (!this._physicsEngine) {
  81290. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81291. return null;
  81292. }
  81293. var impostors = this._physicsEngine.getImpostors();
  81294. if (impostors.length === 0) {
  81295. return null;
  81296. }
  81297. var event = new PhysicsRadialExplosionEvent(this._scene);
  81298. impostors.forEach(function (impostor) {
  81299. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81300. if (!impostorForceAndContactPoint) {
  81301. return;
  81302. }
  81303. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81304. });
  81305. event.dispose(false);
  81306. return event;
  81307. };
  81308. /**
  81309. * @param {Vector3} origin the origin of the explosion
  81310. * @param {number} radius the explosion radius
  81311. * @param {number} strength the explosion strength
  81312. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81313. */
  81314. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  81315. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81316. if (!this._physicsEngine) {
  81317. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81318. return null;
  81319. }
  81320. var impostors = this._physicsEngine.getImpostors();
  81321. if (impostors.length === 0) {
  81322. return null;
  81323. }
  81324. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  81325. event.dispose(false);
  81326. return event;
  81327. };
  81328. /**
  81329. * @param {Vector3} origin the origin of the updraft
  81330. * @param {number} radius the radius of the updraft
  81331. * @param {number} strength the strength of the updraft
  81332. * @param {number} height the height of the updraft
  81333. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  81334. */
  81335. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  81336. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  81337. if (!this._physicsEngine) {
  81338. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81339. return null;
  81340. }
  81341. if (this._physicsEngine.getImpostors().length === 0) {
  81342. return null;
  81343. }
  81344. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  81345. event.dispose(false);
  81346. return event;
  81347. };
  81348. /**
  81349. * @param {Vector3} origin the of the vortex
  81350. * @param {number} radius the radius of the vortex
  81351. * @param {number} strength the strength of the vortex
  81352. * @param {number} height the height of the vortex
  81353. */
  81354. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  81355. if (!this._physicsEngine) {
  81356. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81357. return null;
  81358. }
  81359. if (this._physicsEngine.getImpostors().length === 0) {
  81360. return null;
  81361. }
  81362. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  81363. event.dispose(false);
  81364. return event;
  81365. };
  81366. return PhysicsHelper;
  81367. }());
  81368. BABYLON.PhysicsHelper = PhysicsHelper;
  81369. /***** Radial explosion *****/
  81370. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  81371. function PhysicsRadialExplosionEvent(scene) {
  81372. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  81373. this._rays = [];
  81374. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  81375. this._scene = scene;
  81376. }
  81377. /**
  81378. * Returns the data related to the radial explosion event (sphere & rays).
  81379. * @returns {PhysicsRadialExplosionEventData}
  81380. */
  81381. PhysicsRadialExplosionEvent.prototype.getData = function () {
  81382. this._dataFetched = true;
  81383. return {
  81384. sphere: this._sphere,
  81385. rays: this._rays,
  81386. };
  81387. };
  81388. /**
  81389. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  81390. * @param impostor
  81391. * @param {Vector3} origin the origin of the explosion
  81392. * @param {number} radius the explosion radius
  81393. * @param {number} strength the explosion strength
  81394. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  81395. * @returns {Nullable<PhysicsForceAndContactPoint>}
  81396. */
  81397. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  81398. if (impostor.mass === 0) {
  81399. return null;
  81400. }
  81401. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  81402. return null;
  81403. }
  81404. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81405. return null;
  81406. }
  81407. var impostorObjectCenter = impostor.getObjectCenter();
  81408. var direction = impostorObjectCenter.subtract(origin);
  81409. var ray = new BABYLON.Ray(origin, direction, radius);
  81410. this._rays.push(ray);
  81411. var hit = ray.intersectsMesh(impostor.object);
  81412. var contactPoint = hit.pickedPoint;
  81413. if (!contactPoint) {
  81414. return null;
  81415. }
  81416. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  81417. if (distanceFromOrigin > radius) {
  81418. return null;
  81419. }
  81420. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  81421. ? strength
  81422. : strength * (1 - (distanceFromOrigin / radius));
  81423. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81424. return { force: force, contactPoint: contactPoint };
  81425. };
  81426. /**
  81427. * Disposes the sphere.
  81428. * @param {bolean} force
  81429. */
  81430. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  81431. var _this = this;
  81432. if (force === void 0) { force = true; }
  81433. if (force) {
  81434. this._sphere.dispose();
  81435. }
  81436. else {
  81437. setTimeout(function () {
  81438. if (!_this._dataFetched) {
  81439. _this._sphere.dispose();
  81440. }
  81441. }, 0);
  81442. }
  81443. };
  81444. /*** Helpers ***/
  81445. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  81446. if (!this._sphere) {
  81447. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  81448. this._sphere.isVisible = false;
  81449. }
  81450. };
  81451. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  81452. var impostorObject = impostor.object;
  81453. this._prepareSphere();
  81454. this._sphere.position = origin;
  81455. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  81456. this._sphere._updateBoundingInfo();
  81457. this._sphere.computeWorldMatrix(true);
  81458. return this._sphere.intersectsMesh(impostorObject, true);
  81459. };
  81460. return PhysicsRadialExplosionEvent;
  81461. }());
  81462. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  81463. /***** Gravitational Field *****/
  81464. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  81465. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  81466. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81467. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81468. this._physicsHelper = physicsHelper;
  81469. this._scene = scene;
  81470. this._origin = origin;
  81471. this._radius = radius;
  81472. this._strength = strength;
  81473. this._falloff = falloff;
  81474. this._tickCallback = this._tick.bind(this);
  81475. }
  81476. /**
  81477. * Returns the data related to the gravitational field event (sphere).
  81478. * @returns {PhysicsGravitationalFieldEventData}
  81479. */
  81480. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  81481. this._dataFetched = true;
  81482. return {
  81483. sphere: this._sphere,
  81484. };
  81485. };
  81486. /**
  81487. * Enables the gravitational field.
  81488. */
  81489. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  81490. this._tickCallback.call(this);
  81491. this._scene.registerBeforeRender(this._tickCallback);
  81492. };
  81493. /**
  81494. * Disables the gravitational field.
  81495. */
  81496. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  81497. this._scene.unregisterBeforeRender(this._tickCallback);
  81498. };
  81499. /**
  81500. * Disposes the sphere.
  81501. * @param {bolean} force
  81502. */
  81503. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  81504. var _this = this;
  81505. if (force === void 0) { force = true; }
  81506. if (force) {
  81507. this._sphere.dispose();
  81508. }
  81509. else {
  81510. setTimeout(function () {
  81511. if (!_this._dataFetched) {
  81512. _this._sphere.dispose();
  81513. }
  81514. }, 0);
  81515. }
  81516. };
  81517. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  81518. // Since the params won't change, we fetch the event only once
  81519. if (this._sphere) {
  81520. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81521. }
  81522. else {
  81523. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  81524. if (radialExplosionEvent) {
  81525. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  81526. }
  81527. }
  81528. };
  81529. return PhysicsGravitationalFieldEvent;
  81530. }());
  81531. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  81532. /***** Updraft *****/
  81533. var PhysicsUpdraftEvent = /** @class */ (function () {
  81534. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  81535. this._scene = _scene;
  81536. this._origin = _origin;
  81537. this._radius = _radius;
  81538. this._strength = _strength;
  81539. this._height = _height;
  81540. this._updraftMode = _updraftMode;
  81541. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81542. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  81543. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81544. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81545. this._physicsEngine = this._scene.getPhysicsEngine();
  81546. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81547. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81548. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81549. this._originDirection = this._origin.subtract(this._originTop).normalize();
  81550. }
  81551. this._tickCallback = this._tick.bind(this);
  81552. }
  81553. /**
  81554. * Returns the data related to the updraft event (cylinder).
  81555. * @returns {PhysicsUpdraftEventData}
  81556. */
  81557. PhysicsUpdraftEvent.prototype.getData = function () {
  81558. this._dataFetched = true;
  81559. return {
  81560. cylinder: this._cylinder,
  81561. };
  81562. };
  81563. /**
  81564. * Enables the updraft.
  81565. */
  81566. PhysicsUpdraftEvent.prototype.enable = function () {
  81567. this._tickCallback.call(this);
  81568. this._scene.registerBeforeRender(this._tickCallback);
  81569. };
  81570. /**
  81571. * Disables the cortex.
  81572. */
  81573. PhysicsUpdraftEvent.prototype.disable = function () {
  81574. this._scene.unregisterBeforeRender(this._tickCallback);
  81575. };
  81576. /**
  81577. * Disposes the sphere.
  81578. * @param {bolean} force
  81579. */
  81580. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  81581. var _this = this;
  81582. if (force === void 0) { force = true; }
  81583. if (force) {
  81584. this._cylinder.dispose();
  81585. }
  81586. else {
  81587. setTimeout(function () {
  81588. if (!_this._dataFetched) {
  81589. _this._cylinder.dispose();
  81590. }
  81591. }, 0);
  81592. }
  81593. };
  81594. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81595. if (impostor.mass === 0) {
  81596. return null;
  81597. }
  81598. if (!this._intersectsWithCylinder(impostor)) {
  81599. return null;
  81600. }
  81601. var impostorObjectCenter = impostor.getObjectCenter();
  81602. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81603. var direction = this._originDirection;
  81604. }
  81605. else {
  81606. var direction = impostorObjectCenter.subtract(this._originTop);
  81607. }
  81608. var multiplier = this._strength * -1;
  81609. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81610. return { force: force, contactPoint: impostorObjectCenter };
  81611. };
  81612. PhysicsUpdraftEvent.prototype._tick = function () {
  81613. var _this = this;
  81614. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81615. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81616. if (!impostorForceAndContactPoint) {
  81617. return;
  81618. }
  81619. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81620. });
  81621. };
  81622. /*** Helpers ***/
  81623. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  81624. if (!this._cylinder) {
  81625. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  81626. height: this._height,
  81627. diameter: this._radius * 2,
  81628. }, this._scene);
  81629. this._cylinder.isVisible = false;
  81630. }
  81631. };
  81632. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  81633. var impostorObject = impostor.object;
  81634. this._prepareCylinder();
  81635. this._cylinder.position = this._cylinderPosition;
  81636. return this._cylinder.intersectsMesh(impostorObject, true);
  81637. };
  81638. return PhysicsUpdraftEvent;
  81639. }());
  81640. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  81641. /***** Vortex *****/
  81642. var PhysicsVortexEvent = /** @class */ (function () {
  81643. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  81644. this._scene = _scene;
  81645. this._origin = _origin;
  81646. this._radius = _radius;
  81647. this._strength = _strength;
  81648. this._height = _height;
  81649. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81650. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  81651. this._updraftMultiplier = 0.02;
  81652. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81653. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81654. this._physicsEngine = this._scene.getPhysicsEngine();
  81655. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81656. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81657. this._tickCallback = this._tick.bind(this);
  81658. }
  81659. /**
  81660. * Returns the data related to the vortex event (cylinder).
  81661. * @returns {PhysicsVortexEventData}
  81662. */
  81663. PhysicsVortexEvent.prototype.getData = function () {
  81664. this._dataFetched = true;
  81665. return {
  81666. cylinder: this._cylinder,
  81667. };
  81668. };
  81669. /**
  81670. * Enables the vortex.
  81671. */
  81672. PhysicsVortexEvent.prototype.enable = function () {
  81673. this._tickCallback.call(this);
  81674. this._scene.registerBeforeRender(this._tickCallback);
  81675. };
  81676. /**
  81677. * Disables the cortex.
  81678. */
  81679. PhysicsVortexEvent.prototype.disable = function () {
  81680. this._scene.unregisterBeforeRender(this._tickCallback);
  81681. };
  81682. /**
  81683. * Disposes the sphere.
  81684. * @param {bolean} force
  81685. */
  81686. PhysicsVortexEvent.prototype.dispose = function (force) {
  81687. var _this = this;
  81688. if (force === void 0) { force = true; }
  81689. if (force) {
  81690. this._cylinder.dispose();
  81691. }
  81692. else {
  81693. setTimeout(function () {
  81694. if (!_this._dataFetched) {
  81695. _this._cylinder.dispose();
  81696. }
  81697. }, 0);
  81698. }
  81699. };
  81700. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81701. if (impostor.mass === 0) {
  81702. return null;
  81703. }
  81704. if (!this._intersectsWithCylinder(impostor)) {
  81705. return null;
  81706. }
  81707. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81708. return null;
  81709. }
  81710. var impostorObjectCenter = impostor.getObjectCenter();
  81711. 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)
  81712. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  81713. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  81714. var hit = ray.intersectsMesh(impostor.object);
  81715. var contactPoint = hit.pickedPoint;
  81716. if (!contactPoint) {
  81717. return null;
  81718. }
  81719. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  81720. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  81721. var directionToOrigin = contactPoint.normalize();
  81722. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81723. directionToOrigin = directionToOrigin.negate();
  81724. }
  81725. // TODO: find a more physically based solution
  81726. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81727. var forceX = directionToOrigin.x * this._strength / 8;
  81728. var forceY = directionToOrigin.y * this._updraftMultiplier;
  81729. var forceZ = directionToOrigin.z * this._strength / 8;
  81730. }
  81731. else {
  81732. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  81733. var forceY = this._originTop.y * this._updraftMultiplier;
  81734. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  81735. }
  81736. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  81737. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  81738. return { force: force, contactPoint: impostorObjectCenter };
  81739. };
  81740. PhysicsVortexEvent.prototype._tick = function () {
  81741. var _this = this;
  81742. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81743. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81744. if (!impostorForceAndContactPoint) {
  81745. return;
  81746. }
  81747. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81748. });
  81749. };
  81750. /*** Helpers ***/
  81751. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  81752. if (!this._cylinder) {
  81753. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  81754. height: this._height,
  81755. diameter: this._radius * 2,
  81756. }, this._scene);
  81757. this._cylinder.isVisible = false;
  81758. }
  81759. };
  81760. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  81761. var impostorObject = impostor.object;
  81762. this._prepareCylinder();
  81763. this._cylinder.position = this._cylinderPosition;
  81764. return this._cylinder.intersectsMesh(impostorObject, true);
  81765. };
  81766. return PhysicsVortexEvent;
  81767. }());
  81768. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  81769. /***** Enums *****/
  81770. /**
  81771. * The strenght of the force in correspondence to the distance of the affected object
  81772. */
  81773. var PhysicsRadialImpulseFalloff;
  81774. (function (PhysicsRadialImpulseFalloff) {
  81775. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  81776. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  81777. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  81778. /**
  81779. * The strenght of the force in correspondence to the distance of the affected object
  81780. */
  81781. var PhysicsUpdraftMode;
  81782. (function (PhysicsUpdraftMode) {
  81783. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  81784. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  81785. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  81786. })(BABYLON || (BABYLON = {}));
  81787. //# sourceMappingURL=babylon.physicsHelper.js.map
  81788. "use strict";
  81789. var BABYLON;
  81790. (function (BABYLON) {
  81791. var CannonJSPlugin = /** @class */ (function () {
  81792. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  81793. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  81794. if (iterations === void 0) { iterations = 10; }
  81795. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  81796. this.name = "CannonJSPlugin";
  81797. this._physicsMaterials = new Array();
  81798. this._fixedTimeStep = 1 / 60;
  81799. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  81800. this.BJSCANNON = CANNON;
  81801. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  81802. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  81803. this._tmpPosition = BABYLON.Vector3.Zero();
  81804. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  81805. this._tmpUnityRotation = new BABYLON.Quaternion();
  81806. if (!this.isSupported()) {
  81807. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  81808. return;
  81809. }
  81810. this._extendNamespace();
  81811. this.world = new this.BJSCANNON.World();
  81812. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  81813. this.world.solver.iterations = iterations;
  81814. }
  81815. CannonJSPlugin.prototype.setGravity = function (gravity) {
  81816. this.world.gravity.copy(gravity);
  81817. };
  81818. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  81819. this._fixedTimeStep = timeStep;
  81820. };
  81821. CannonJSPlugin.prototype.getTimeStep = function () {
  81822. return this._fixedTimeStep;
  81823. };
  81824. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  81825. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  81826. };
  81827. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81828. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81829. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81830. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  81831. };
  81832. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81833. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81834. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81835. impostor.physicsBody.applyForce(impulse, worldPoint);
  81836. };
  81837. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81838. //parent-child relationship. Does this impostor has a parent impostor?
  81839. if (impostor.parent) {
  81840. if (impostor.physicsBody) {
  81841. this.removePhysicsBody(impostor);
  81842. //TODO is that needed?
  81843. impostor.forceUpdate();
  81844. }
  81845. return;
  81846. }
  81847. //should a new body be created for this impostor?
  81848. if (impostor.isBodyInitRequired()) {
  81849. var shape = this._createShape(impostor);
  81850. //unregister events, if body is being changed
  81851. var oldBody = impostor.physicsBody;
  81852. if (oldBody) {
  81853. this.removePhysicsBody(impostor);
  81854. }
  81855. //create the body and material
  81856. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  81857. var bodyCreationObject = {
  81858. mass: impostor.getParam("mass"),
  81859. material: material
  81860. };
  81861. // A simple extend, in case native options were used.
  81862. var nativeOptions = impostor.getParam("nativeOptions");
  81863. for (var key in nativeOptions) {
  81864. if (nativeOptions.hasOwnProperty(key)) {
  81865. bodyCreationObject[key] = nativeOptions[key];
  81866. }
  81867. }
  81868. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  81869. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  81870. this.world.addEventListener("preStep", impostor.beforeStep);
  81871. this.world.addEventListener("postStep", impostor.afterStep);
  81872. impostor.physicsBody.addShape(shape);
  81873. this.world.add(impostor.physicsBody);
  81874. //try to keep the body moving in the right direction by taking old properties.
  81875. //Should be tested!
  81876. if (oldBody) {
  81877. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  81878. impostor.physicsBody[param].copy(oldBody[param]);
  81879. });
  81880. }
  81881. this._processChildMeshes(impostor);
  81882. }
  81883. //now update the body's transformation
  81884. this._updatePhysicsBodyTransformation(impostor);
  81885. };
  81886. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  81887. var _this = this;
  81888. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  81889. var currentRotation = mainImpostor.object.rotationQuaternion;
  81890. if (meshChildren.length) {
  81891. var processMesh = function (localPosition, mesh) {
  81892. if (!currentRotation || !mesh.rotationQuaternion) {
  81893. return;
  81894. }
  81895. var childImpostor = mesh.getPhysicsImpostor();
  81896. if (childImpostor) {
  81897. var parent = childImpostor.parent;
  81898. if (parent !== mainImpostor) {
  81899. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  81900. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  81901. if (childImpostor.physicsBody) {
  81902. _this.removePhysicsBody(childImpostor);
  81903. childImpostor.physicsBody = null;
  81904. }
  81905. childImpostor.parent = mainImpostor;
  81906. childImpostor.resetUpdateFlags();
  81907. 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));
  81908. //Add the mass of the children.
  81909. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  81910. }
  81911. }
  81912. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  81913. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  81914. };
  81915. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  81916. }
  81917. };
  81918. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81919. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  81920. this.world.removeEventListener("preStep", impostor.beforeStep);
  81921. this.world.removeEventListener("postStep", impostor.afterStep);
  81922. this.world.remove(impostor.physicsBody);
  81923. };
  81924. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81925. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81926. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81927. if (!mainBody || !connectedBody) {
  81928. return;
  81929. }
  81930. var constraint;
  81931. var jointData = impostorJoint.joint.jointData;
  81932. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  81933. var constraintData = {
  81934. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  81935. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  81936. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  81937. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  81938. maxForce: jointData.nativeParams.maxForce,
  81939. collideConnected: !!jointData.collision
  81940. };
  81941. switch (impostorJoint.joint.type) {
  81942. case BABYLON.PhysicsJoint.HingeJoint:
  81943. case BABYLON.PhysicsJoint.Hinge2Joint:
  81944. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  81945. break;
  81946. case BABYLON.PhysicsJoint.DistanceJoint:
  81947. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  81948. break;
  81949. case BABYLON.PhysicsJoint.SpringJoint:
  81950. var springData = jointData;
  81951. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  81952. restLength: springData.length,
  81953. stiffness: springData.stiffness,
  81954. damping: springData.damping,
  81955. localAnchorA: constraintData.pivotA,
  81956. localAnchorB: constraintData.pivotB
  81957. });
  81958. break;
  81959. case BABYLON.PhysicsJoint.LockJoint:
  81960. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  81961. break;
  81962. case BABYLON.PhysicsJoint.PointToPointJoint:
  81963. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81964. default:
  81965. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  81966. break;
  81967. }
  81968. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  81969. constraint.collideConnected = !!jointData.collision;
  81970. impostorJoint.joint.physicsJoint = constraint;
  81971. //don't add spring as constraint, as it is not one.
  81972. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  81973. this.world.addConstraint(constraint);
  81974. }
  81975. else {
  81976. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  81977. constraint.applyForce();
  81978. });
  81979. }
  81980. };
  81981. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81982. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  81983. };
  81984. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  81985. var index;
  81986. var mat;
  81987. for (index = 0; index < this._physicsMaterials.length; index++) {
  81988. mat = this._physicsMaterials[index];
  81989. if (mat.friction === friction && mat.restitution === restitution) {
  81990. return mat;
  81991. }
  81992. }
  81993. var currentMat = new this.BJSCANNON.Material(name);
  81994. currentMat.friction = friction;
  81995. currentMat.restitution = restitution;
  81996. this._physicsMaterials.push(currentMat);
  81997. return currentMat;
  81998. };
  81999. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  82000. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  82001. };
  82002. CannonJSPlugin.prototype._createShape = function (impostor) {
  82003. var object = impostor.object;
  82004. var returnValue;
  82005. var extendSize = impostor.getObjectExtendSize();
  82006. switch (impostor.type) {
  82007. case BABYLON.PhysicsImpostor.SphereImpostor:
  82008. var radiusX = extendSize.x;
  82009. var radiusY = extendSize.y;
  82010. var radiusZ = extendSize.z;
  82011. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  82012. break;
  82013. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  82014. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82015. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  82016. break;
  82017. case BABYLON.PhysicsImpostor.BoxImpostor:
  82018. var box = extendSize.scale(0.5);
  82019. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  82020. break;
  82021. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82022. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  82023. returnValue = new this.BJSCANNON.Plane();
  82024. break;
  82025. case BABYLON.PhysicsImpostor.MeshImpostor:
  82026. // should transform the vertex data to world coordinates!!
  82027. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  82028. var rawFaces = object.getIndices ? object.getIndices() : [];
  82029. if (!rawVerts)
  82030. return;
  82031. // get only scale! so the object could transform correctly.
  82032. var oldPosition = object.position.clone();
  82033. var oldRotation = object.rotation && object.rotation.clone();
  82034. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  82035. object.position.copyFromFloats(0, 0, 0);
  82036. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82037. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82038. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82039. var transform = object.computeWorldMatrix(true);
  82040. // convert rawVerts to object space
  82041. var temp = new Array();
  82042. var index;
  82043. for (index = 0; index < rawVerts.length; index += 3) {
  82044. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  82045. }
  82046. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  82047. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  82048. //now set back the transformation!
  82049. object.position.copyFrom(oldPosition);
  82050. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  82051. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  82052. break;
  82053. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  82054. var oldPosition2 = object.position.clone();
  82055. var oldRotation2 = object.rotation && object.rotation.clone();
  82056. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  82057. object.position.copyFromFloats(0, 0, 0);
  82058. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82059. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82060. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82061. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  82062. returnValue = this._createHeightmap(object);
  82063. object.position.copyFrom(oldPosition2);
  82064. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  82065. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  82066. object.computeWorldMatrix(true);
  82067. break;
  82068. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82069. returnValue = new this.BJSCANNON.Particle();
  82070. break;
  82071. }
  82072. return returnValue;
  82073. };
  82074. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  82075. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  82076. var transform = object.computeWorldMatrix(true);
  82077. // convert rawVerts to object space
  82078. var temp = new Array();
  82079. var index;
  82080. for (index = 0; index < pos.length; index += 3) {
  82081. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  82082. }
  82083. pos = temp;
  82084. var matrix = new Array();
  82085. //For now pointDepth will not be used and will be automatically calculated.
  82086. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  82087. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  82088. var boundingInfo = object.getBoundingInfo();
  82089. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  82090. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  82091. var elementSize = dim * 2 / arraySize;
  82092. for (var i = 0; i < pos.length; i = i + 3) {
  82093. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  82094. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  82095. var y = -pos[i + 2] + minY;
  82096. if (!matrix[x]) {
  82097. matrix[x] = [];
  82098. }
  82099. if (!matrix[x][z]) {
  82100. matrix[x][z] = y;
  82101. }
  82102. matrix[x][z] = Math.max(y, matrix[x][z]);
  82103. }
  82104. for (var x = 0; x <= arraySize; ++x) {
  82105. if (!matrix[x]) {
  82106. var loc = 1;
  82107. while (!matrix[(x + loc) % arraySize]) {
  82108. loc++;
  82109. }
  82110. matrix[x] = matrix[(x + loc) % arraySize].slice();
  82111. //console.log("missing x", x);
  82112. }
  82113. for (var z = 0; z <= arraySize; ++z) {
  82114. if (!matrix[x][z]) {
  82115. var loc = 1;
  82116. var newValue;
  82117. while (newValue === undefined) {
  82118. newValue = matrix[x][(z + loc++) % arraySize];
  82119. }
  82120. matrix[x][z] = newValue;
  82121. }
  82122. }
  82123. }
  82124. var shape = new this.BJSCANNON.Heightfield(matrix, {
  82125. elementSize: elementSize
  82126. });
  82127. //For future reference, needed for body transformation
  82128. shape.minY = minY;
  82129. return shape;
  82130. };
  82131. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  82132. var object = impostor.object;
  82133. //make sure it is updated...
  82134. object.computeWorldMatrix && object.computeWorldMatrix(true);
  82135. // The delta between the mesh position and the mesh bounding box center
  82136. var bInfo = object.getBoundingInfo();
  82137. if (!bInfo)
  82138. return;
  82139. var center = impostor.getObjectCenter();
  82140. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  82141. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  82142. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  82143. this._tmpPosition.copyFrom(center);
  82144. var quaternion = object.rotationQuaternion;
  82145. if (!quaternion) {
  82146. return;
  82147. }
  82148. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  82149. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  82150. //-90 DEG in X, precalculated
  82151. quaternion = quaternion.multiply(this._minus90X);
  82152. //Invert! (Precalculated, 90 deg in X)
  82153. //No need to clone. this will never change.
  82154. impostor.setDeltaRotation(this._plus90X);
  82155. }
  82156. //If it is a heightfield, if should be centered.
  82157. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  82158. var mesh = object;
  82159. var boundingInfo = mesh.getBoundingInfo();
  82160. //calculate the correct body position:
  82161. var rotationQuaternion = mesh.rotationQuaternion;
  82162. mesh.rotationQuaternion = this._tmpUnityRotation;
  82163. mesh.computeWorldMatrix(true);
  82164. //get original center with no rotation
  82165. var c = center.clone();
  82166. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  82167. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  82168. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  82169. mesh.setPreTransformMatrix(p);
  82170. mesh.computeWorldMatrix(true);
  82171. //calculate the translation
  82172. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  82173. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  82174. //add it inverted to the delta
  82175. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  82176. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  82177. //rotation is back
  82178. mesh.rotationQuaternion = rotationQuaternion;
  82179. mesh.setPreTransformMatrix(oldPivot);
  82180. mesh.computeWorldMatrix(true);
  82181. }
  82182. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  82183. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  82184. //this._tmpPosition.copyFrom(object.position);
  82185. }
  82186. impostor.setDeltaPosition(this._tmpDeltaPosition);
  82187. //Now update the impostor object
  82188. impostor.physicsBody.position.copy(this._tmpPosition);
  82189. impostor.physicsBody.quaternion.copy(quaternion);
  82190. };
  82191. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82192. impostor.object.position.copyFrom(impostor.physicsBody.position);
  82193. if (impostor.object.rotationQuaternion) {
  82194. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  82195. }
  82196. };
  82197. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82198. impostor.physicsBody.position.copy(newPosition);
  82199. impostor.physicsBody.quaternion.copy(newRotation);
  82200. };
  82201. CannonJSPlugin.prototype.isSupported = function () {
  82202. return this.BJSCANNON !== undefined;
  82203. };
  82204. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82205. impostor.physicsBody.velocity.copy(velocity);
  82206. };
  82207. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82208. impostor.physicsBody.angularVelocity.copy(velocity);
  82209. };
  82210. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82211. var v = impostor.physicsBody.velocity;
  82212. if (!v) {
  82213. return null;
  82214. }
  82215. return new BABYLON.Vector3(v.x, v.y, v.z);
  82216. };
  82217. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82218. var v = impostor.physicsBody.angularVelocity;
  82219. if (!v) {
  82220. return null;
  82221. }
  82222. return new BABYLON.Vector3(v.x, v.y, v.z);
  82223. };
  82224. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82225. impostor.physicsBody.mass = mass;
  82226. impostor.physicsBody.updateMassProperties();
  82227. };
  82228. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82229. return impostor.physicsBody.mass;
  82230. };
  82231. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82232. return impostor.physicsBody.material.friction;
  82233. };
  82234. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82235. impostor.physicsBody.material.friction = friction;
  82236. };
  82237. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82238. return impostor.physicsBody.material.restitution;
  82239. };
  82240. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82241. impostor.physicsBody.material.restitution = restitution;
  82242. };
  82243. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82244. impostor.physicsBody.sleep();
  82245. };
  82246. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82247. impostor.physicsBody.wakeUp();
  82248. };
  82249. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82250. joint.physicsJoint.distance = maxDistance;
  82251. };
  82252. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82253. // if (!motorIndex) {
  82254. // joint.physicsJoint.enableMotor();
  82255. // }
  82256. // }
  82257. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82258. // if (!motorIndex) {
  82259. // joint.physicsJoint.disableMotor();
  82260. // }
  82261. // }
  82262. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82263. if (!motorIndex) {
  82264. joint.physicsJoint.enableMotor();
  82265. joint.physicsJoint.setMotorSpeed(speed);
  82266. if (maxForce) {
  82267. this.setLimit(joint, maxForce);
  82268. }
  82269. }
  82270. };
  82271. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  82272. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  82273. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  82274. };
  82275. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82276. var body = impostor.physicsBody;
  82277. mesh.position.x = body.position.x;
  82278. mesh.position.y = body.position.y;
  82279. mesh.position.z = body.position.z;
  82280. if (mesh.rotationQuaternion) {
  82281. mesh.rotationQuaternion.x = body.quaternion.x;
  82282. mesh.rotationQuaternion.y = body.quaternion.y;
  82283. mesh.rotationQuaternion.z = body.quaternion.z;
  82284. mesh.rotationQuaternion.w = body.quaternion.w;
  82285. }
  82286. };
  82287. CannonJSPlugin.prototype.getRadius = function (impostor) {
  82288. var shape = impostor.physicsBody.shapes[0];
  82289. return shape.boundingSphereRadius;
  82290. };
  82291. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82292. var shape = impostor.physicsBody.shapes[0];
  82293. result.x = shape.halfExtents.x * 2;
  82294. result.y = shape.halfExtents.y * 2;
  82295. result.z = shape.halfExtents.z * 2;
  82296. };
  82297. CannonJSPlugin.prototype.dispose = function () {
  82298. };
  82299. CannonJSPlugin.prototype._extendNamespace = function () {
  82300. //this will force cannon to execute at least one step when using interpolation
  82301. var step_tmp1 = new this.BJSCANNON.Vec3();
  82302. var Engine = this.BJSCANNON;
  82303. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  82304. maxSubSteps = maxSubSteps || 10;
  82305. timeSinceLastCalled = timeSinceLastCalled || 0;
  82306. if (timeSinceLastCalled === 0) {
  82307. this.internalStep(dt);
  82308. this.time += dt;
  82309. }
  82310. else {
  82311. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  82312. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  82313. var t0 = performance.now();
  82314. for (var i = 0; i !== internalSteps; i++) {
  82315. this.internalStep(dt);
  82316. if (performance.now() - t0 > dt * 1000) {
  82317. break;
  82318. }
  82319. }
  82320. this.time += timeSinceLastCalled;
  82321. var h = this.time % dt;
  82322. var h_div_dt = h / dt;
  82323. var interpvelo = step_tmp1;
  82324. var bodies = this.bodies;
  82325. for (var j = 0; j !== bodies.length; j++) {
  82326. var b = bodies[j];
  82327. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  82328. b.position.vsub(b.previousPosition, interpvelo);
  82329. interpvelo.scale(h_div_dt, interpvelo);
  82330. b.position.vadd(interpvelo, b.interpolatedPosition);
  82331. }
  82332. else {
  82333. b.interpolatedPosition.copy(b.position);
  82334. b.interpolatedQuaternion.copy(b.quaternion);
  82335. }
  82336. }
  82337. }
  82338. };
  82339. };
  82340. return CannonJSPlugin;
  82341. }());
  82342. BABYLON.CannonJSPlugin = CannonJSPlugin;
  82343. })(BABYLON || (BABYLON = {}));
  82344. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  82345. "use strict";
  82346. var BABYLON;
  82347. (function (BABYLON) {
  82348. var OimoJSPlugin = /** @class */ (function () {
  82349. function OimoJSPlugin(iterations) {
  82350. this.name = "OimoJSPlugin";
  82351. this._tmpImpostorsArray = [];
  82352. this._tmpPositionVector = BABYLON.Vector3.Zero();
  82353. this.BJSOIMO = OIMO;
  82354. this.world = new this.BJSOIMO.World({
  82355. iterations: iterations
  82356. });
  82357. this.world.clear();
  82358. }
  82359. OimoJSPlugin.prototype.setGravity = function (gravity) {
  82360. this.world.gravity.copy(gravity);
  82361. };
  82362. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  82363. this.world.timeStep = timeStep;
  82364. };
  82365. OimoJSPlugin.prototype.getTimeStep = function () {
  82366. return this.world.timeStep;
  82367. };
  82368. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  82369. var _this = this;
  82370. impostors.forEach(function (impostor) {
  82371. impostor.beforeStep();
  82372. });
  82373. this.world.step();
  82374. impostors.forEach(function (impostor) {
  82375. impostor.afterStep();
  82376. //update the ordered impostors array
  82377. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  82378. });
  82379. //check for collisions
  82380. var contact = this.world.contacts;
  82381. while (contact !== null) {
  82382. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  82383. contact = contact.next;
  82384. continue;
  82385. }
  82386. //is this body colliding with any other? get the impostor
  82387. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  82388. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  82389. if (!mainImpostor || !collidingImpostor) {
  82390. contact = contact.next;
  82391. continue;
  82392. }
  82393. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  82394. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  82395. contact = contact.next;
  82396. }
  82397. };
  82398. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82399. var mass = impostor.physicsBody.mass;
  82400. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  82401. };
  82402. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82403. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  82404. this.applyImpulse(impostor, force, contactPoint);
  82405. };
  82406. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82407. var _this = this;
  82408. //parent-child relationship. Does this impostor has a parent impostor?
  82409. if (impostor.parent) {
  82410. if (impostor.physicsBody) {
  82411. this.removePhysicsBody(impostor);
  82412. //TODO is that needed?
  82413. impostor.forceUpdate();
  82414. }
  82415. return;
  82416. }
  82417. if (impostor.isBodyInitRequired()) {
  82418. var bodyConfig = {
  82419. name: impostor.uniqueId,
  82420. //Oimo must have mass, also for static objects.
  82421. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  82422. size: [],
  82423. type: [],
  82424. pos: [],
  82425. posShape: [],
  82426. rot: [],
  82427. rotShape: [],
  82428. move: impostor.getParam("mass") !== 0,
  82429. density: impostor.getParam("mass"),
  82430. friction: impostor.getParam("friction"),
  82431. restitution: impostor.getParam("restitution"),
  82432. //Supporting older versions of Oimo
  82433. world: this.world
  82434. };
  82435. var impostors = [impostor];
  82436. var addToArray = function (parent) {
  82437. if (!parent.getChildMeshes)
  82438. return;
  82439. parent.getChildMeshes().forEach(function (m) {
  82440. if (m.physicsImpostor) {
  82441. impostors.push(m.physicsImpostor);
  82442. //m.physicsImpostor._init();
  82443. }
  82444. });
  82445. };
  82446. addToArray(impostor.object);
  82447. var checkWithEpsilon_1 = function (value) {
  82448. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  82449. };
  82450. impostors.forEach(function (i) {
  82451. if (!i.object.rotationQuaternion) {
  82452. return;
  82453. }
  82454. //get the correct bounding box
  82455. var oldQuaternion = i.object.rotationQuaternion;
  82456. var rot = oldQuaternion.toEulerAngles();
  82457. var extendSize = i.getObjectExtendSize();
  82458. var radToDeg = 57.295779513082320876;
  82459. if (i === impostor) {
  82460. var center = impostor.getObjectCenter();
  82461. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  82462. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  82463. //Can also use Array.prototype.push.apply
  82464. bodyConfig.pos.push(center.x);
  82465. bodyConfig.pos.push(center.y);
  82466. bodyConfig.pos.push(center.z);
  82467. bodyConfig.posShape.push(0, 0, 0);
  82468. //tmp solution
  82469. bodyConfig.rot.push(rot.x * radToDeg);
  82470. bodyConfig.rot.push(rot.y * radToDeg);
  82471. bodyConfig.rot.push(rot.z * radToDeg);
  82472. bodyConfig.rotShape.push(0, 0, 0);
  82473. }
  82474. else {
  82475. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  82476. bodyConfig.posShape.push(localPosition.x);
  82477. bodyConfig.posShape.push(localPosition.y);
  82478. bodyConfig.posShape.push(localPosition.z);
  82479. bodyConfig.pos.push(0, 0, 0);
  82480. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  82481. bodyConfig.rot.push(0);
  82482. bodyConfig.rot.push(0);
  82483. bodyConfig.rot.push(0);
  82484. bodyConfig.rotShape.push(rot.x * radToDeg);
  82485. bodyConfig.rotShape.push(rot.y * radToDeg);
  82486. bodyConfig.rotShape.push(rot.z * radToDeg);
  82487. }
  82488. // register mesh
  82489. switch (i.type) {
  82490. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82491. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  82492. case BABYLON.PhysicsImpostor.SphereImpostor:
  82493. var radiusX = extendSize.x;
  82494. var radiusY = extendSize.y;
  82495. var radiusZ = extendSize.z;
  82496. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  82497. bodyConfig.type.push('sphere');
  82498. //due to the way oimo works with compounds, add 3 times
  82499. bodyConfig.size.push(size);
  82500. bodyConfig.size.push(size);
  82501. bodyConfig.size.push(size);
  82502. break;
  82503. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82504. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  82505. var sizeY = checkWithEpsilon_1(extendSize.y);
  82506. bodyConfig.type.push('cylinder');
  82507. bodyConfig.size.push(sizeX);
  82508. bodyConfig.size.push(sizeY);
  82509. //due to the way oimo works with compounds, add one more value.
  82510. bodyConfig.size.push(sizeY);
  82511. break;
  82512. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82513. case BABYLON.PhysicsImpostor.BoxImpostor:
  82514. default:
  82515. var sizeX = checkWithEpsilon_1(extendSize.x);
  82516. var sizeY = checkWithEpsilon_1(extendSize.y);
  82517. var sizeZ = checkWithEpsilon_1(extendSize.z);
  82518. bodyConfig.type.push('box');
  82519. //if (i === impostor) {
  82520. bodyConfig.size.push(sizeX);
  82521. bodyConfig.size.push(sizeY);
  82522. bodyConfig.size.push(sizeZ);
  82523. //} else {
  82524. // bodyConfig.size.push(0,0,0);
  82525. //}
  82526. break;
  82527. }
  82528. //actually not needed, but hey...
  82529. i.object.rotationQuaternion = oldQuaternion;
  82530. });
  82531. impostor.physicsBody = this.world.add(bodyConfig);
  82532. }
  82533. else {
  82534. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  82535. }
  82536. impostor.setDeltaPosition(this._tmpPositionVector);
  82537. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  82538. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  82539. };
  82540. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82541. //impostor.physicsBody.dispose();
  82542. //Same as : (older oimo versions)
  82543. this.world.removeRigidBody(impostor.physicsBody);
  82544. };
  82545. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82546. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82547. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82548. if (!mainBody || !connectedBody) {
  82549. return;
  82550. }
  82551. var jointData = impostorJoint.joint.jointData;
  82552. var options = jointData.nativeParams || {};
  82553. var type;
  82554. var nativeJointData = {
  82555. body1: mainBody,
  82556. body2: connectedBody,
  82557. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  82558. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  82559. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  82560. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  82561. min: options.min,
  82562. max: options.max,
  82563. collision: options.collision || jointData.collision,
  82564. spring: options.spring,
  82565. //supporting older version of Oimo
  82566. world: this.world
  82567. };
  82568. switch (impostorJoint.joint.type) {
  82569. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82570. type = "jointBall";
  82571. break;
  82572. case BABYLON.PhysicsJoint.SpringJoint:
  82573. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  82574. var springData = jointData;
  82575. nativeJointData.min = springData.length || nativeJointData.min;
  82576. //Max should also be set, just make sure it is at least min
  82577. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  82578. case BABYLON.PhysicsJoint.DistanceJoint:
  82579. type = "jointDistance";
  82580. nativeJointData.max = jointData.maxDistance;
  82581. break;
  82582. case BABYLON.PhysicsJoint.PrismaticJoint:
  82583. type = "jointPrisme";
  82584. break;
  82585. case BABYLON.PhysicsJoint.SliderJoint:
  82586. type = "jointSlide";
  82587. break;
  82588. case BABYLON.PhysicsJoint.WheelJoint:
  82589. type = "jointWheel";
  82590. break;
  82591. case BABYLON.PhysicsJoint.HingeJoint:
  82592. default:
  82593. type = "jointHinge";
  82594. break;
  82595. }
  82596. nativeJointData.type = type;
  82597. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  82598. };
  82599. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82600. //Bug in Oimo prevents us from disposing a joint in the playground
  82601. //joint.joint.physicsJoint.dispose();
  82602. //So we will bruteforce it!
  82603. try {
  82604. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  82605. }
  82606. catch (e) {
  82607. BABYLON.Tools.Warn(e);
  82608. }
  82609. };
  82610. OimoJSPlugin.prototype.isSupported = function () {
  82611. return this.BJSOIMO !== undefined;
  82612. };
  82613. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82614. if (!impostor.physicsBody.sleeping) {
  82615. //TODO check that
  82616. /*if (impostor.physicsBody.shapes.next) {
  82617. var parentShape = this._getLastShape(impostor.physicsBody);
  82618. impostor.object.position.copyFrom(parentShape.position);
  82619. console.log(parentShape.position);
  82620. } else {*/
  82621. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  82622. //}
  82623. if (impostor.object.rotationQuaternion) {
  82624. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  82625. }
  82626. }
  82627. };
  82628. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82629. var body = impostor.physicsBody;
  82630. body.position.copy(newPosition);
  82631. body.orientation.copy(newRotation);
  82632. body.syncShapes();
  82633. body.awake();
  82634. };
  82635. /*private _getLastShape(body: any): any {
  82636. var lastShape = body.shapes;
  82637. while (lastShape.next) {
  82638. lastShape = lastShape.next;
  82639. }
  82640. return lastShape;
  82641. }*/
  82642. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82643. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  82644. };
  82645. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82646. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  82647. };
  82648. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82649. var v = impostor.physicsBody.linearVelocity;
  82650. if (!v) {
  82651. return null;
  82652. }
  82653. return new BABYLON.Vector3(v.x, v.y, v.z);
  82654. };
  82655. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82656. var v = impostor.physicsBody.angularVelocity;
  82657. if (!v) {
  82658. return null;
  82659. }
  82660. return new BABYLON.Vector3(v.x, v.y, v.z);
  82661. };
  82662. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82663. var staticBody = mass === 0;
  82664. //this will actually set the body's density and not its mass.
  82665. //But this is how oimo treats the mass variable.
  82666. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  82667. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  82668. };
  82669. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  82670. return impostor.physicsBody.shapes.density;
  82671. };
  82672. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  82673. return impostor.physicsBody.shapes.friction;
  82674. };
  82675. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82676. impostor.physicsBody.shapes.friction = friction;
  82677. };
  82678. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82679. return impostor.physicsBody.shapes.restitution;
  82680. };
  82681. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82682. impostor.physicsBody.shapes.restitution = restitution;
  82683. };
  82684. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  82685. impostor.physicsBody.sleep();
  82686. };
  82687. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  82688. impostor.physicsBody.awake();
  82689. };
  82690. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82691. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  82692. if (minDistance !== void 0) {
  82693. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  82694. }
  82695. };
  82696. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82697. //TODO separate rotational and transational motors.
  82698. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82699. if (motor) {
  82700. motor.setMotor(speed, maxForce);
  82701. }
  82702. };
  82703. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  82704. //TODO separate rotational and transational motors.
  82705. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82706. if (motor) {
  82707. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  82708. }
  82709. };
  82710. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82711. var body = impostor.physicsBody;
  82712. mesh.position.x = body.position.x;
  82713. mesh.position.y = body.position.y;
  82714. mesh.position.z = body.position.z;
  82715. if (mesh.rotationQuaternion) {
  82716. mesh.rotationQuaternion.x = body.orientation.x;
  82717. mesh.rotationQuaternion.y = body.orientation.y;
  82718. mesh.rotationQuaternion.z = body.orientation.z;
  82719. mesh.rotationQuaternion.w = body.orientation.s;
  82720. }
  82721. };
  82722. OimoJSPlugin.prototype.getRadius = function (impostor) {
  82723. return impostor.physicsBody.shapes.radius;
  82724. };
  82725. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82726. var shape = impostor.physicsBody.shapes;
  82727. result.x = shape.halfWidth * 2;
  82728. result.y = shape.halfHeight * 2;
  82729. result.z = shape.halfDepth * 2;
  82730. };
  82731. OimoJSPlugin.prototype.dispose = function () {
  82732. this.world.clear();
  82733. };
  82734. return OimoJSPlugin;
  82735. }());
  82736. BABYLON.OimoJSPlugin = OimoJSPlugin;
  82737. })(BABYLON || (BABYLON = {}));
  82738. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  82739. "use strict";
  82740. var BABYLON;
  82741. (function (BABYLON) {
  82742. /*
  82743. * Based on jsTGALoader - Javascript loader for TGA file
  82744. * By Vincent Thibault
  82745. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  82746. */
  82747. var TGATools = /** @class */ (function () {
  82748. function TGATools() {
  82749. }
  82750. TGATools.GetTGAHeader = function (data) {
  82751. var offset = 0;
  82752. var header = {
  82753. id_length: data[offset++],
  82754. colormap_type: data[offset++],
  82755. image_type: data[offset++],
  82756. colormap_index: data[offset++] | data[offset++] << 8,
  82757. colormap_length: data[offset++] | data[offset++] << 8,
  82758. colormap_size: data[offset++],
  82759. origin: [
  82760. data[offset++] | data[offset++] << 8,
  82761. data[offset++] | data[offset++] << 8
  82762. ],
  82763. width: data[offset++] | data[offset++] << 8,
  82764. height: data[offset++] | data[offset++] << 8,
  82765. pixel_size: data[offset++],
  82766. flags: data[offset++]
  82767. };
  82768. return header;
  82769. };
  82770. TGATools.UploadContent = function (gl, data) {
  82771. // Not enough data to contain header ?
  82772. if (data.length < 19) {
  82773. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  82774. return;
  82775. }
  82776. // Read Header
  82777. var offset = 18;
  82778. var header = TGATools.GetTGAHeader(data);
  82779. // Assume it's a valid Targa file.
  82780. if (header.id_length + offset > data.length) {
  82781. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  82782. return;
  82783. }
  82784. // Skip not needed data
  82785. offset += header.id_length;
  82786. var use_rle = false;
  82787. var use_pal = false;
  82788. var use_grey = false;
  82789. // Get some informations.
  82790. switch (header.image_type) {
  82791. case TGATools._TYPE_RLE_INDEXED:
  82792. use_rle = true;
  82793. case TGATools._TYPE_INDEXED:
  82794. use_pal = true;
  82795. break;
  82796. case TGATools._TYPE_RLE_RGB:
  82797. use_rle = true;
  82798. case TGATools._TYPE_RGB:
  82799. // use_rgb = true;
  82800. break;
  82801. case TGATools._TYPE_RLE_GREY:
  82802. use_rle = true;
  82803. case TGATools._TYPE_GREY:
  82804. use_grey = true;
  82805. break;
  82806. }
  82807. var pixel_data;
  82808. // var numAlphaBits = header.flags & 0xf;
  82809. var pixel_size = header.pixel_size >> 3;
  82810. var pixel_total = header.width * header.height * pixel_size;
  82811. // Read palettes
  82812. var palettes;
  82813. if (use_pal) {
  82814. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  82815. }
  82816. // Read LRE
  82817. if (use_rle) {
  82818. pixel_data = new Uint8Array(pixel_total);
  82819. var c, count, i;
  82820. var localOffset = 0;
  82821. var pixels = new Uint8Array(pixel_size);
  82822. while (offset < pixel_total && localOffset < pixel_total) {
  82823. c = data[offset++];
  82824. count = (c & 0x7f) + 1;
  82825. // RLE pixels
  82826. if (c & 0x80) {
  82827. // Bind pixel tmp array
  82828. for (i = 0; i < pixel_size; ++i) {
  82829. pixels[i] = data[offset++];
  82830. }
  82831. // Copy pixel array
  82832. for (i = 0; i < count; ++i) {
  82833. pixel_data.set(pixels, localOffset + i * pixel_size);
  82834. }
  82835. localOffset += pixel_size * count;
  82836. }
  82837. else {
  82838. count *= pixel_size;
  82839. for (i = 0; i < count; ++i) {
  82840. pixel_data[localOffset + i] = data[offset++];
  82841. }
  82842. localOffset += count;
  82843. }
  82844. }
  82845. }
  82846. else {
  82847. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  82848. }
  82849. // Load to texture
  82850. var x_start, y_start, x_step, y_step, y_end, x_end;
  82851. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  82852. default:
  82853. case TGATools._ORIGIN_UL:
  82854. x_start = 0;
  82855. x_step = 1;
  82856. x_end = header.width;
  82857. y_start = 0;
  82858. y_step = 1;
  82859. y_end = header.height;
  82860. break;
  82861. case TGATools._ORIGIN_BL:
  82862. x_start = 0;
  82863. x_step = 1;
  82864. x_end = header.width;
  82865. y_start = header.height - 1;
  82866. y_step = -1;
  82867. y_end = -1;
  82868. break;
  82869. case TGATools._ORIGIN_UR:
  82870. x_start = header.width - 1;
  82871. x_step = -1;
  82872. x_end = -1;
  82873. y_start = 0;
  82874. y_step = 1;
  82875. y_end = header.height;
  82876. break;
  82877. case TGATools._ORIGIN_BR:
  82878. x_start = header.width - 1;
  82879. x_step = -1;
  82880. x_end = -1;
  82881. y_start = header.height - 1;
  82882. y_step = -1;
  82883. y_end = -1;
  82884. break;
  82885. }
  82886. // Load the specify method
  82887. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  82888. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  82889. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  82890. };
  82891. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82892. var image = pixel_data, colormap = palettes;
  82893. var width = header.width, height = header.height;
  82894. var color, i = 0, x, y;
  82895. var imageData = new Uint8Array(width * height * 4);
  82896. for (y = y_start; y !== y_end; y += y_step) {
  82897. for (x = x_start; x !== x_end; x += x_step, i++) {
  82898. color = image[i];
  82899. imageData[(x + width * y) * 4 + 3] = 255;
  82900. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  82901. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  82902. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  82903. }
  82904. }
  82905. return imageData;
  82906. };
  82907. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82908. var image = pixel_data;
  82909. var width = header.width, height = header.height;
  82910. var color, i = 0, x, y;
  82911. var imageData = new Uint8Array(width * height * 4);
  82912. for (y = y_start; y !== y_end; y += y_step) {
  82913. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82914. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  82915. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  82916. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  82917. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  82918. imageData[(x + width * y) * 4 + 0] = r;
  82919. imageData[(x + width * y) * 4 + 1] = g;
  82920. imageData[(x + width * y) * 4 + 2] = b;
  82921. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  82922. }
  82923. }
  82924. return imageData;
  82925. };
  82926. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82927. var image = pixel_data;
  82928. var width = header.width, height = header.height;
  82929. var i = 0, x, y;
  82930. var imageData = new Uint8Array(width * height * 4);
  82931. for (y = y_start; y !== y_end; y += y_step) {
  82932. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  82933. imageData[(x + width * y) * 4 + 3] = 255;
  82934. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82935. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82936. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82937. }
  82938. }
  82939. return imageData;
  82940. };
  82941. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82942. var image = pixel_data;
  82943. var width = header.width, height = header.height;
  82944. var i = 0, x, y;
  82945. var imageData = new Uint8Array(width * height * 4);
  82946. for (y = y_start; y !== y_end; y += y_step) {
  82947. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  82948. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82949. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82950. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82951. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  82952. }
  82953. }
  82954. return imageData;
  82955. };
  82956. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82957. var image = pixel_data;
  82958. var width = header.width, height = header.height;
  82959. var color, i = 0, x, y;
  82960. var imageData = new Uint8Array(width * height * 4);
  82961. for (y = y_start; y !== y_end; y += y_step) {
  82962. for (x = x_start; x !== x_end; x += x_step, i++) {
  82963. color = image[i];
  82964. imageData[(x + width * y) * 4 + 0] = color;
  82965. imageData[(x + width * y) * 4 + 1] = color;
  82966. imageData[(x + width * y) * 4 + 2] = color;
  82967. imageData[(x + width * y) * 4 + 3] = 255;
  82968. }
  82969. }
  82970. return imageData;
  82971. };
  82972. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82973. var image = pixel_data;
  82974. var width = header.width, height = header.height;
  82975. var i = 0, x, y;
  82976. var imageData = new Uint8Array(width * height * 4);
  82977. for (y = y_start; y !== y_end; y += y_step) {
  82978. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82979. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  82980. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  82981. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82982. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  82983. }
  82984. }
  82985. return imageData;
  82986. };
  82987. //private static _TYPE_NO_DATA = 0;
  82988. TGATools._TYPE_INDEXED = 1;
  82989. TGATools._TYPE_RGB = 2;
  82990. TGATools._TYPE_GREY = 3;
  82991. TGATools._TYPE_RLE_INDEXED = 9;
  82992. TGATools._TYPE_RLE_RGB = 10;
  82993. TGATools._TYPE_RLE_GREY = 11;
  82994. TGATools._ORIGIN_MASK = 0x30;
  82995. TGATools._ORIGIN_SHIFT = 0x04;
  82996. TGATools._ORIGIN_BL = 0x00;
  82997. TGATools._ORIGIN_BR = 0x01;
  82998. TGATools._ORIGIN_UL = 0x02;
  82999. TGATools._ORIGIN_UR = 0x03;
  83000. return TGATools;
  83001. }());
  83002. BABYLON.TGATools = TGATools;
  83003. })(BABYLON || (BABYLON = {}));
  83004. //# sourceMappingURL=babylon.tga.js.map
  83005. "use strict";
  83006. var BABYLON;
  83007. (function (BABYLON) {
  83008. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  83009. // All values and structures referenced from:
  83010. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  83011. var DDS_MAGIC = 0x20534444;
  83012. var
  83013. //DDSD_CAPS = 0x1,
  83014. //DDSD_HEIGHT = 0x2,
  83015. //DDSD_WIDTH = 0x4,
  83016. //DDSD_PITCH = 0x8,
  83017. //DDSD_PIXELFORMAT = 0x1000,
  83018. DDSD_MIPMAPCOUNT = 0x20000;
  83019. //DDSD_LINEARSIZE = 0x80000,
  83020. //DDSD_DEPTH = 0x800000;
  83021. // var DDSCAPS_COMPLEX = 0x8,
  83022. // DDSCAPS_MIPMAP = 0x400000,
  83023. // DDSCAPS_TEXTURE = 0x1000;
  83024. var DDSCAPS2_CUBEMAP = 0x200;
  83025. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  83026. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  83027. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  83028. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  83029. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  83030. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  83031. // DDSCAPS2_VOLUME = 0x200000;
  83032. var
  83033. //DDPF_ALPHAPIXELS = 0x1,
  83034. //DDPF_ALPHA = 0x2,
  83035. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  83036. //DDPF_YUV = 0x200,
  83037. DDPF_LUMINANCE = 0x20000;
  83038. function FourCCToInt32(value) {
  83039. return value.charCodeAt(0) +
  83040. (value.charCodeAt(1) << 8) +
  83041. (value.charCodeAt(2) << 16) +
  83042. (value.charCodeAt(3) << 24);
  83043. }
  83044. function Int32ToFourCC(value) {
  83045. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  83046. }
  83047. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  83048. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  83049. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  83050. var FOURCC_DX10 = FourCCToInt32("DX10");
  83051. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  83052. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  83053. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  83054. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  83055. var headerLengthInt = 31; // The header length in 32 bit ints
  83056. // Offsets into the header array
  83057. var off_magic = 0;
  83058. var off_size = 1;
  83059. var off_flags = 2;
  83060. var off_height = 3;
  83061. var off_width = 4;
  83062. var off_mipmapCount = 7;
  83063. var off_pfFlags = 20;
  83064. var off_pfFourCC = 21;
  83065. var off_RGBbpp = 22;
  83066. var off_RMask = 23;
  83067. var off_GMask = 24;
  83068. var off_BMask = 25;
  83069. var off_AMask = 26;
  83070. // var off_caps1 = 27;
  83071. var off_caps2 = 28;
  83072. // var off_caps3 = 29;
  83073. // var off_caps4 = 30;
  83074. var off_dxgiFormat = 32;
  83075. ;
  83076. var DDSTools = /** @class */ (function () {
  83077. function DDSTools() {
  83078. }
  83079. DDSTools.GetDDSInfo = function (arrayBuffer) {
  83080. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83081. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  83082. var mipmapCount = 1;
  83083. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  83084. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83085. }
  83086. var fourCC = header[off_pfFourCC];
  83087. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  83088. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83089. switch (fourCC) {
  83090. case FOURCC_D3DFMT_R16G16B16A16F:
  83091. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83092. break;
  83093. case FOURCC_D3DFMT_R32G32B32A32F:
  83094. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83095. break;
  83096. case FOURCC_DX10:
  83097. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  83098. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83099. break;
  83100. }
  83101. }
  83102. return {
  83103. width: header[off_width],
  83104. height: header[off_height],
  83105. mipmapCount: mipmapCount,
  83106. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  83107. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  83108. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  83109. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  83110. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  83111. dxgiFormat: dxgiFormat,
  83112. textureType: textureType
  83113. };
  83114. };
  83115. DDSTools._ToHalfFloat = function (value) {
  83116. if (!DDSTools._FloatView) {
  83117. DDSTools._FloatView = new Float32Array(1);
  83118. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  83119. }
  83120. DDSTools._FloatView[0] = value;
  83121. var x = DDSTools._Int32View[0];
  83122. var bits = (x >> 16) & 0x8000; /* Get the sign */
  83123. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  83124. var e = (x >> 23) & 0xff; /* Using int is faster here */
  83125. /* If zero, or denormal, or exponent underflows too much for a denormal
  83126. * half, return signed zero. */
  83127. if (e < 103) {
  83128. return bits;
  83129. }
  83130. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  83131. if (e > 142) {
  83132. bits |= 0x7c00;
  83133. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  83134. * not Inf, so make sure we set one mantissa bit too. */
  83135. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  83136. return bits;
  83137. }
  83138. /* If exponent underflows but not too much, return a denormal */
  83139. if (e < 113) {
  83140. m |= 0x0800;
  83141. /* Extra rounding may overflow and set mantissa to 0 and exponent
  83142. * to 1, which is OK. */
  83143. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  83144. return bits;
  83145. }
  83146. bits |= ((e - 112) << 10) | (m >> 1);
  83147. bits += m & 1;
  83148. return bits;
  83149. };
  83150. DDSTools._FromHalfFloat = function (value) {
  83151. var s = (value & 0x8000) >> 15;
  83152. var e = (value & 0x7C00) >> 10;
  83153. var f = value & 0x03FF;
  83154. if (e === 0) {
  83155. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  83156. }
  83157. else if (e == 0x1F) {
  83158. return f ? NaN : ((s ? -1 : 1) * Infinity);
  83159. }
  83160. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  83161. };
  83162. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83163. var destArray = new Float32Array(dataLength);
  83164. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83165. var index = 0;
  83166. for (var y = 0; y < height; y++) {
  83167. for (var x = 0; x < width; x++) {
  83168. var srcPos = (x + y * width) * 4;
  83169. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  83170. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  83171. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  83172. if (DDSTools.StoreLODInAlphaChannel) {
  83173. destArray[index + 3] = lod;
  83174. }
  83175. else {
  83176. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  83177. }
  83178. index += 4;
  83179. }
  83180. }
  83181. return destArray;
  83182. };
  83183. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83184. if (DDSTools.StoreLODInAlphaChannel) {
  83185. var destArray = new Uint16Array(dataLength);
  83186. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83187. var index = 0;
  83188. for (var y = 0; y < height; y++) {
  83189. for (var x = 0; x < width; x++) {
  83190. var srcPos = (x + y * width) * 4;
  83191. destArray[index] = srcData[srcPos];
  83192. destArray[index + 1] = srcData[srcPos + 1];
  83193. destArray[index + 2] = srcData[srcPos + 2];
  83194. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  83195. index += 4;
  83196. }
  83197. }
  83198. return destArray;
  83199. }
  83200. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  83201. };
  83202. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83203. if (DDSTools.StoreLODInAlphaChannel) {
  83204. var destArray = new Float32Array(dataLength);
  83205. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83206. var index = 0;
  83207. for (var y = 0; y < height; y++) {
  83208. for (var x = 0; x < width; x++) {
  83209. var srcPos = (x + y * width) * 4;
  83210. destArray[index] = srcData[srcPos];
  83211. destArray[index + 1] = srcData[srcPos + 1];
  83212. destArray[index + 2] = srcData[srcPos + 2];
  83213. destArray[index + 3] = lod;
  83214. index += 4;
  83215. }
  83216. }
  83217. return destArray;
  83218. }
  83219. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83220. };
  83221. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83222. var destArray = new Uint8Array(dataLength);
  83223. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83224. var index = 0;
  83225. for (var y = 0; y < height; y++) {
  83226. for (var x = 0; x < width; x++) {
  83227. var srcPos = (x + y * width) * 4;
  83228. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83229. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83230. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83231. if (DDSTools.StoreLODInAlphaChannel) {
  83232. destArray[index + 3] = lod;
  83233. }
  83234. else {
  83235. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83236. }
  83237. index += 4;
  83238. }
  83239. }
  83240. return destArray;
  83241. };
  83242. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83243. var destArray = new Uint8Array(dataLength);
  83244. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83245. var index = 0;
  83246. for (var y = 0; y < height; y++) {
  83247. for (var x = 0; x < width; x++) {
  83248. var srcPos = (x + y * width) * 4;
  83249. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83250. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83251. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83252. if (DDSTools.StoreLODInAlphaChannel) {
  83253. destArray[index + 3] = lod;
  83254. }
  83255. else {
  83256. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83257. }
  83258. index += 4;
  83259. }
  83260. }
  83261. return destArray;
  83262. };
  83263. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83264. var byteArray = new Uint8Array(dataLength);
  83265. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83266. var index = 0;
  83267. for (var y = 0; y < height; y++) {
  83268. for (var x = 0; x < width; x++) {
  83269. var srcPos = (x + y * width) * 4;
  83270. byteArray[index] = srcData[srcPos + rOffset];
  83271. byteArray[index + 1] = srcData[srcPos + gOffset];
  83272. byteArray[index + 2] = srcData[srcPos + bOffset];
  83273. byteArray[index + 3] = srcData[srcPos + aOffset];
  83274. index += 4;
  83275. }
  83276. }
  83277. return byteArray;
  83278. };
  83279. DDSTools._ExtractLongWordOrder = function (value) {
  83280. if (value === 0 || value === 255 || value === -16777216) {
  83281. return 0;
  83282. }
  83283. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  83284. };
  83285. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  83286. var byteArray = new Uint8Array(dataLength);
  83287. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83288. var index = 0;
  83289. for (var y = 0; y < height; y++) {
  83290. for (var x = 0; x < width; x++) {
  83291. var srcPos = (x + y * width) * 3;
  83292. byteArray[index] = srcData[srcPos + rOffset];
  83293. byteArray[index + 1] = srcData[srcPos + gOffset];
  83294. byteArray[index + 2] = srcData[srcPos + bOffset];
  83295. index += 3;
  83296. }
  83297. }
  83298. return byteArray;
  83299. };
  83300. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  83301. var byteArray = new Uint8Array(dataLength);
  83302. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83303. var index = 0;
  83304. for (var y = 0; y < height; y++) {
  83305. for (var x = 0; x < width; x++) {
  83306. var srcPos = (x + y * width);
  83307. byteArray[index] = srcData[srcPos];
  83308. index++;
  83309. }
  83310. }
  83311. return byteArray;
  83312. };
  83313. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  83314. if (lodIndex === void 0) { lodIndex = -1; }
  83315. var ext = engine.getCaps().s3tc;
  83316. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83317. var fourCC, width, height, dataLength = 0, dataOffset;
  83318. var byteArray, mipmapCount, mip;
  83319. var internalFormat = 0;
  83320. var format = 0;
  83321. var blockBytes = 1;
  83322. if (header[off_magic] !== DDS_MAGIC) {
  83323. BABYLON.Tools.Error("Invalid magic number in DDS header");
  83324. return;
  83325. }
  83326. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  83327. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  83328. return;
  83329. }
  83330. if (info.isCompressed && !ext) {
  83331. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  83332. return;
  83333. }
  83334. var bpp = header[off_RGBbpp];
  83335. dataOffset = header[off_size] + 4;
  83336. var computeFormats = false;
  83337. if (info.isFourCC) {
  83338. fourCC = header[off_pfFourCC];
  83339. switch (fourCC) {
  83340. case FOURCC_DXT1:
  83341. blockBytes = 8;
  83342. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  83343. break;
  83344. case FOURCC_DXT3:
  83345. blockBytes = 16;
  83346. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  83347. break;
  83348. case FOURCC_DXT5:
  83349. blockBytes = 16;
  83350. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  83351. break;
  83352. case FOURCC_D3DFMT_R16G16B16A16F:
  83353. computeFormats = true;
  83354. break;
  83355. case FOURCC_D3DFMT_R32G32B32A32F:
  83356. computeFormats = true;
  83357. break;
  83358. case FOURCC_DX10:
  83359. // There is an additionnal header so dataOffset need to be changed
  83360. dataOffset += 5 * 4; // 5 uints
  83361. var supported = false;
  83362. switch (info.dxgiFormat) {
  83363. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  83364. computeFormats = true;
  83365. supported = true;
  83366. break;
  83367. case DXGI_FORMAT_B8G8R8X8_UNORM:
  83368. info.isRGB = true;
  83369. info.isFourCC = false;
  83370. bpp = 32;
  83371. supported = true;
  83372. break;
  83373. }
  83374. if (supported) {
  83375. break;
  83376. }
  83377. default:
  83378. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  83379. return;
  83380. }
  83381. }
  83382. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  83383. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  83384. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  83385. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  83386. if (computeFormats) {
  83387. format = engine._getWebGLTextureType(info.textureType);
  83388. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83389. }
  83390. mipmapCount = 1;
  83391. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  83392. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83393. }
  83394. for (var face = 0; face < faces; face++) {
  83395. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  83396. width = header[off_width];
  83397. height = header[off_height];
  83398. for (mip = 0; mip < mipmapCount; ++mip) {
  83399. if (lodIndex === -1 || lodIndex === mip) {
  83400. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  83401. var i = (lodIndex === -1) ? mip : 0;
  83402. if (!info.isCompressed && info.isFourCC) {
  83403. dataLength = width * height * 4;
  83404. var floatArray = null;
  83405. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  83406. if (bpp === 128) {
  83407. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83408. }
  83409. else if (bpp === 64) {
  83410. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83411. }
  83412. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83413. format = engine._getWebGLTextureType(info.textureType);
  83414. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83415. }
  83416. else {
  83417. if (bpp === 128) {
  83418. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83419. }
  83420. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  83421. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83422. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83423. format = engine._getWebGLTextureType(info.textureType);
  83424. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83425. }
  83426. else {
  83427. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83428. }
  83429. }
  83430. if (floatArray) {
  83431. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  83432. }
  83433. }
  83434. else if (info.isRGB) {
  83435. if (bpp === 24) {
  83436. dataLength = width * height * 3;
  83437. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  83438. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  83439. }
  83440. else {
  83441. dataLength = width * height * 4;
  83442. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  83443. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  83444. }
  83445. }
  83446. else if (info.isLuminance) {
  83447. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  83448. var unpaddedRowSize = width;
  83449. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  83450. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  83451. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  83452. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  83453. }
  83454. else {
  83455. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  83456. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  83457. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  83458. }
  83459. }
  83460. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  83461. width *= 0.5;
  83462. height *= 0.5;
  83463. width = Math.max(1.0, width);
  83464. height = Math.max(1.0, height);
  83465. }
  83466. if (currentFace !== undefined) {
  83467. // Loading a single face
  83468. break;
  83469. }
  83470. }
  83471. };
  83472. DDSTools.StoreLODInAlphaChannel = false;
  83473. return DDSTools;
  83474. }());
  83475. BABYLON.DDSTools = DDSTools;
  83476. })(BABYLON || (BABYLON = {}));
  83477. //# sourceMappingURL=babylon.dds.js.map
  83478. "use strict";
  83479. var BABYLON;
  83480. (function (BABYLON) {
  83481. /**
  83482. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  83483. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  83484. */
  83485. var KhronosTextureContainer = /** @class */ (function () {
  83486. /**
  83487. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  83488. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  83489. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  83490. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  83491. */
  83492. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  83493. this.arrayBuffer = arrayBuffer;
  83494. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  83495. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  83496. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  83497. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  83498. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  83499. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  83500. BABYLON.Tools.Error("texture missing KTX identifier");
  83501. return;
  83502. }
  83503. // load the reset of the header in native 32 bit int
  83504. var header = new Int32Array(this.arrayBuffer, 12, 13);
  83505. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  83506. var oppositeEndianess = header[0] === 0x01020304;
  83507. // read all the header elements in order they exist in the file, without modification (sans endainness)
  83508. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  83509. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  83510. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  83511. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  83512. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  83513. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  83514. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  83515. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  83516. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  83517. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  83518. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  83519. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  83520. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  83521. if (this.glType !== 0) {
  83522. BABYLON.Tools.Error("only compressed formats currently supported");
  83523. return;
  83524. }
  83525. else {
  83526. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  83527. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  83528. }
  83529. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  83530. BABYLON.Tools.Error("only 2D textures currently supported");
  83531. return;
  83532. }
  83533. if (this.numberOfArrayElements !== 0) {
  83534. BABYLON.Tools.Error("texture arrays not currently supported");
  83535. return;
  83536. }
  83537. if (this.numberOfFaces !== facesExpected) {
  83538. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  83539. return;
  83540. }
  83541. // we now have a completely validated file, so could use existence of loadType as success
  83542. // would need to make this more elaborate & adjust checks above to support more than one load type
  83543. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  83544. }
  83545. // not as fast hardware based, but will probably never need to use
  83546. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  83547. return ((val & 0xFF) << 24)
  83548. | ((val & 0xFF00) << 8)
  83549. | ((val >> 8) & 0xFF00)
  83550. | ((val >> 24) & 0xFF);
  83551. };
  83552. /**
  83553. * It is assumed that the texture has already been created & is currently bound
  83554. */
  83555. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  83556. switch (this.loadType) {
  83557. case KhronosTextureContainer.COMPRESSED_2D:
  83558. this._upload2DCompressedLevels(gl, loadMipmaps);
  83559. break;
  83560. case KhronosTextureContainer.TEX_2D:
  83561. case KhronosTextureContainer.COMPRESSED_3D:
  83562. case KhronosTextureContainer.TEX_3D:
  83563. }
  83564. };
  83565. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  83566. // initialize width & height for level 1
  83567. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  83568. var width = this.pixelWidth;
  83569. var height = this.pixelHeight;
  83570. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  83571. for (var level = 0; level < mipmapCount; level++) {
  83572. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  83573. for (var face = 0; face < this.numberOfFaces; face++) {
  83574. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  83575. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  83576. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  83577. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  83578. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  83579. }
  83580. width = Math.max(1.0, width * 0.5);
  83581. height = Math.max(1.0, height * 0.5);
  83582. }
  83583. };
  83584. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  83585. // load types
  83586. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  83587. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  83588. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  83589. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  83590. return KhronosTextureContainer;
  83591. }());
  83592. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  83593. })(BABYLON || (BABYLON = {}));
  83594. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  83595. "use strict";
  83596. var BABYLON;
  83597. (function (BABYLON) {
  83598. var Debug;
  83599. (function (Debug) {
  83600. /**
  83601. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  83602. */
  83603. var SkeletonViewer = /** @class */ (function () {
  83604. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  83605. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  83606. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  83607. this.skeleton = skeleton;
  83608. this.mesh = mesh;
  83609. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  83610. this.renderingGroupId = renderingGroupId;
  83611. this.color = BABYLON.Color3.White();
  83612. this._debugLines = new Array();
  83613. this._isEnabled = false;
  83614. this._scene = scene;
  83615. this.update();
  83616. this._renderFunction = this.update.bind(this);
  83617. }
  83618. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  83619. get: function () {
  83620. return this._isEnabled;
  83621. },
  83622. set: function (value) {
  83623. if (this._isEnabled === value) {
  83624. return;
  83625. }
  83626. this._isEnabled = value;
  83627. if (value) {
  83628. this._scene.registerBeforeRender(this._renderFunction);
  83629. }
  83630. else {
  83631. this._scene.unregisterBeforeRender(this._renderFunction);
  83632. }
  83633. },
  83634. enumerable: true,
  83635. configurable: true
  83636. });
  83637. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  83638. if (x === void 0) { x = 0; }
  83639. if (y === void 0) { y = 0; }
  83640. if (z === void 0) { z = 0; }
  83641. var tmat = BABYLON.Tmp.Matrix[0];
  83642. var parentBone = bone.getParent();
  83643. tmat.copyFrom(bone.getLocalMatrix());
  83644. if (x !== 0 || y !== 0 || z !== 0) {
  83645. var tmat2 = BABYLON.Tmp.Matrix[1];
  83646. BABYLON.Matrix.IdentityToRef(tmat2);
  83647. tmat2.m[12] = x;
  83648. tmat2.m[13] = y;
  83649. tmat2.m[14] = z;
  83650. tmat2.multiplyToRef(tmat, tmat);
  83651. }
  83652. if (parentBone) {
  83653. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  83654. }
  83655. tmat.multiplyToRef(meshMat, tmat);
  83656. position.x = tmat.m[12];
  83657. position.y = tmat.m[13];
  83658. position.z = tmat.m[14];
  83659. };
  83660. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  83661. var len = bones.length;
  83662. var meshPos = this.mesh.position;
  83663. for (var i = 0; i < len; i++) {
  83664. var bone = bones[i];
  83665. var points = this._debugLines[i];
  83666. if (!points) {
  83667. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83668. this._debugLines[i] = points;
  83669. }
  83670. this._getBonePosition(points[0], bone, meshMat);
  83671. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  83672. points[0].subtractInPlace(meshPos);
  83673. points[1].subtractInPlace(meshPos);
  83674. }
  83675. };
  83676. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  83677. var len = bones.length;
  83678. var boneNum = 0;
  83679. var meshPos = this.mesh.position;
  83680. for (var i = len - 1; i >= 0; i--) {
  83681. var childBone = bones[i];
  83682. var parentBone = childBone.getParent();
  83683. if (!parentBone) {
  83684. continue;
  83685. }
  83686. var points = this._debugLines[boneNum];
  83687. if (!points) {
  83688. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83689. this._debugLines[boneNum] = points;
  83690. }
  83691. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  83692. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  83693. points[0].subtractInPlace(meshPos);
  83694. points[1].subtractInPlace(meshPos);
  83695. boneNum++;
  83696. }
  83697. };
  83698. SkeletonViewer.prototype.update = function () {
  83699. if (this.autoUpdateBonesMatrices) {
  83700. this.skeleton.computeAbsoluteTransforms();
  83701. }
  83702. if (this.skeleton.bones[0].length === undefined) {
  83703. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83704. }
  83705. else {
  83706. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83707. }
  83708. if (!this._debugMesh) {
  83709. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  83710. this._debugMesh.renderingGroupId = this.renderingGroupId;
  83711. }
  83712. else {
  83713. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  83714. }
  83715. this._debugMesh.position.copyFrom(this.mesh.position);
  83716. this._debugMesh.color = this.color;
  83717. };
  83718. SkeletonViewer.prototype.dispose = function () {
  83719. if (this._debugMesh) {
  83720. this.isEnabled = false;
  83721. this._debugMesh.dispose();
  83722. this._debugMesh = null;
  83723. }
  83724. };
  83725. return SkeletonViewer;
  83726. }());
  83727. Debug.SkeletonViewer = SkeletonViewer;
  83728. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83729. })(BABYLON || (BABYLON = {}));
  83730. //# sourceMappingURL=babylon.skeletonViewer.js.map
  83731. "use strict";
  83732. /**
  83733. * Module Debug contains the (visual) components to debug a scene correctly
  83734. */
  83735. var BABYLON;
  83736. (function (BABYLON) {
  83737. var Debug;
  83738. (function (Debug) {
  83739. /**
  83740. * The Axes viewer will show 3 axes in a specific point in space
  83741. */
  83742. var AxesViewer = /** @class */ (function () {
  83743. function AxesViewer(scene, scaleLines) {
  83744. if (scaleLines === void 0) { scaleLines = 1; }
  83745. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83746. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83747. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83748. this.scaleLines = 1;
  83749. this.scaleLines = scaleLines;
  83750. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  83751. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  83752. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  83753. this._xmesh.renderingGroupId = 2;
  83754. this._ymesh.renderingGroupId = 2;
  83755. this._zmesh.renderingGroupId = 2;
  83756. this._xmesh.material.checkReadyOnlyOnce = true;
  83757. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  83758. this._ymesh.material.checkReadyOnlyOnce = true;
  83759. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  83760. this._zmesh.material.checkReadyOnlyOnce = true;
  83761. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  83762. this.scene = scene;
  83763. }
  83764. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  83765. var scaleLines = this.scaleLines;
  83766. if (this._xmesh) {
  83767. this._xmesh.position.copyFrom(position);
  83768. }
  83769. if (this._ymesh) {
  83770. this._ymesh.position.copyFrom(position);
  83771. }
  83772. if (this._zmesh) {
  83773. this._zmesh.position.copyFrom(position);
  83774. }
  83775. var point2 = this._xline[1];
  83776. point2.x = xaxis.x * scaleLines;
  83777. point2.y = xaxis.y * scaleLines;
  83778. point2.z = xaxis.z * scaleLines;
  83779. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  83780. point2 = this._yline[1];
  83781. point2.x = yaxis.x * scaleLines;
  83782. point2.y = yaxis.y * scaleLines;
  83783. point2.z = yaxis.z * scaleLines;
  83784. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  83785. point2 = this._zline[1];
  83786. point2.x = zaxis.x * scaleLines;
  83787. point2.y = zaxis.y * scaleLines;
  83788. point2.z = zaxis.z * scaleLines;
  83789. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  83790. };
  83791. AxesViewer.prototype.dispose = function () {
  83792. if (this._xmesh) {
  83793. this._xmesh.dispose();
  83794. }
  83795. if (this._ymesh) {
  83796. this._ymesh.dispose();
  83797. }
  83798. if (this._zmesh) {
  83799. this._zmesh.dispose();
  83800. }
  83801. this._xmesh = null;
  83802. this._ymesh = null;
  83803. this._zmesh = null;
  83804. this.scene = null;
  83805. };
  83806. return AxesViewer;
  83807. }());
  83808. Debug.AxesViewer = AxesViewer;
  83809. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83810. })(BABYLON || (BABYLON = {}));
  83811. //# sourceMappingURL=babylon.axesViewer.js.map
  83812. "use strict";
  83813. var BABYLON;
  83814. (function (BABYLON) {
  83815. var Debug;
  83816. (function (Debug) {
  83817. /**
  83818. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  83819. */
  83820. var BoneAxesViewer = /** @class */ (function (_super) {
  83821. __extends(BoneAxesViewer, _super);
  83822. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  83823. if (scaleLines === void 0) { scaleLines = 1; }
  83824. var _this = _super.call(this, scene, scaleLines) || this;
  83825. _this.pos = BABYLON.Vector3.Zero();
  83826. _this.xaxis = BABYLON.Vector3.Zero();
  83827. _this.yaxis = BABYLON.Vector3.Zero();
  83828. _this.zaxis = BABYLON.Vector3.Zero();
  83829. _this.mesh = mesh;
  83830. _this.bone = bone;
  83831. return _this;
  83832. }
  83833. BoneAxesViewer.prototype.update = function () {
  83834. if (!this.mesh || !this.bone) {
  83835. return;
  83836. }
  83837. var bone = this.bone;
  83838. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  83839. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  83840. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  83841. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  83842. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  83843. };
  83844. BoneAxesViewer.prototype.dispose = function () {
  83845. if (this.mesh) {
  83846. this.mesh = null;
  83847. this.bone = null;
  83848. _super.prototype.dispose.call(this);
  83849. }
  83850. };
  83851. return BoneAxesViewer;
  83852. }(Debug.AxesViewer));
  83853. Debug.BoneAxesViewer = BoneAxesViewer;
  83854. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83855. })(BABYLON || (BABYLON = {}));
  83856. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  83857. "use strict";
  83858. var BABYLON;
  83859. (function (BABYLON) {
  83860. var RayHelper = /** @class */ (function () {
  83861. function RayHelper(ray) {
  83862. this.ray = ray;
  83863. }
  83864. RayHelper.CreateAndShow = function (ray, scene, color) {
  83865. var helper = new RayHelper(ray);
  83866. helper.show(scene, color);
  83867. return helper;
  83868. };
  83869. RayHelper.prototype.show = function (scene, color) {
  83870. if (!this._renderFunction && this.ray) {
  83871. var ray = this.ray;
  83872. this._renderFunction = this._render.bind(this);
  83873. this._scene = scene;
  83874. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  83875. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  83876. if (this._renderFunction) {
  83877. this._scene.registerBeforeRender(this._renderFunction);
  83878. }
  83879. }
  83880. if (color && this._renderLine) {
  83881. this._renderLine.color.copyFrom(color);
  83882. }
  83883. };
  83884. RayHelper.prototype.hide = function () {
  83885. if (this._renderFunction && this._scene) {
  83886. this._scene.unregisterBeforeRender(this._renderFunction);
  83887. this._scene = null;
  83888. this._renderFunction = null;
  83889. if (this._renderLine) {
  83890. this._renderLine.dispose();
  83891. this._renderLine = null;
  83892. }
  83893. this._renderPoints = [];
  83894. }
  83895. };
  83896. RayHelper.prototype._render = function () {
  83897. var ray = this.ray;
  83898. if (!ray) {
  83899. return;
  83900. }
  83901. var point = this._renderPoints[1];
  83902. var len = Math.min(ray.length, 1000000);
  83903. point.copyFrom(ray.direction);
  83904. point.scaleInPlace(len);
  83905. point.addInPlace(ray.origin);
  83906. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  83907. };
  83908. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  83909. this._attachedToMesh = mesh;
  83910. var ray = this.ray;
  83911. if (!ray) {
  83912. return;
  83913. }
  83914. if (!ray.direction) {
  83915. ray.direction = BABYLON.Vector3.Zero();
  83916. }
  83917. if (!ray.origin) {
  83918. ray.origin = BABYLON.Vector3.Zero();
  83919. }
  83920. if (length) {
  83921. ray.length = length;
  83922. }
  83923. if (!meshSpaceOrigin) {
  83924. meshSpaceOrigin = BABYLON.Vector3.Zero();
  83925. }
  83926. if (!meshSpaceDirection) {
  83927. // -1 so that this will work with Mesh.lookAt
  83928. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  83929. }
  83930. if (!this._meshSpaceDirection) {
  83931. this._meshSpaceDirection = meshSpaceDirection.clone();
  83932. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  83933. }
  83934. else {
  83935. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  83936. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  83937. }
  83938. if (!this._updateToMeshFunction) {
  83939. this._updateToMeshFunction = this._updateToMesh.bind(this);
  83940. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  83941. }
  83942. this._updateToMesh();
  83943. };
  83944. RayHelper.prototype.detachFromMesh = function () {
  83945. if (this._attachedToMesh) {
  83946. if (this._updateToMeshFunction) {
  83947. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  83948. }
  83949. this._attachedToMesh = null;
  83950. this._updateToMeshFunction = null;
  83951. }
  83952. };
  83953. RayHelper.prototype._updateToMesh = function () {
  83954. var ray = this.ray;
  83955. if (!this._attachedToMesh || !ray) {
  83956. return;
  83957. }
  83958. if (this._attachedToMesh._isDisposed) {
  83959. this.detachFromMesh();
  83960. return;
  83961. }
  83962. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  83963. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  83964. };
  83965. RayHelper.prototype.dispose = function () {
  83966. this.hide();
  83967. this.detachFromMesh();
  83968. this.ray = null;
  83969. };
  83970. return RayHelper;
  83971. }());
  83972. BABYLON.RayHelper = RayHelper;
  83973. })(BABYLON || (BABYLON = {}));
  83974. //# sourceMappingURL=babylon.rayHelper.js.map
  83975. "use strict";
  83976. var BABYLON;
  83977. (function (BABYLON) {
  83978. // load the inspector using require, if not present in the global namespace.
  83979. var DebugLayer = /** @class */ (function () {
  83980. function DebugLayer(scene) {
  83981. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83982. this._scene = scene;
  83983. // load inspector using require, if it doesn't exist on the global namespace.
  83984. }
  83985. /** Creates the inspector window. */
  83986. DebugLayer.prototype._createInspector = function (config) {
  83987. if (config === void 0) { config = {}; }
  83988. var popup = config.popup || false;
  83989. var initialTab = config.initialTab || 0;
  83990. var parentElement = config.parentElement || null;
  83991. if (!this._inspector) {
  83992. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83993. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  83994. } // else nothing to do,; instance is already existing
  83995. };
  83996. DebugLayer.prototype.isVisible = function () {
  83997. if (!this._inspector) {
  83998. return false;
  83999. }
  84000. return true;
  84001. };
  84002. DebugLayer.prototype.hide = function () {
  84003. if (this._inspector) {
  84004. try {
  84005. this._inspector.dispose();
  84006. }
  84007. catch (e) {
  84008. // If the inspector has been removed directly from the inspector tool
  84009. }
  84010. this._inspector = null;
  84011. }
  84012. };
  84013. DebugLayer.prototype.show = function (config) {
  84014. if (config === void 0) { config = {}; }
  84015. if (typeof this.BJSINSPECTOR == 'undefined') {
  84016. // Load inspector and add it to the DOM
  84017. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  84018. }
  84019. else {
  84020. // Otherwise creates the inspector
  84021. this._createInspector(config);
  84022. }
  84023. };
  84024. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  84025. return DebugLayer;
  84026. }());
  84027. BABYLON.DebugLayer = DebugLayer;
  84028. })(BABYLON || (BABYLON = {}));
  84029. //# sourceMappingURL=babylon.debugLayer.js.map
  84030. "use strict";
  84031. var BABYLON;
  84032. (function (BABYLON) {
  84033. var Debug;
  84034. (function (Debug) {
  84035. /**
  84036. * Used to show the physics impostor around the specific mesh.
  84037. */
  84038. var PhysicsViewer = /** @class */ (function () {
  84039. function PhysicsViewer(scene) {
  84040. this._impostors = [];
  84041. this._meshes = [];
  84042. this._numMeshes = 0;
  84043. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84044. var physicEngine = this._scene.getPhysicsEngine();
  84045. if (physicEngine) {
  84046. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  84047. }
  84048. }
  84049. PhysicsViewer.prototype._updateDebugMeshes = function () {
  84050. var plugin = this._physicsEnginePlugin;
  84051. for (var i = 0; i < this._numMeshes; i++) {
  84052. var impostor = this._impostors[i];
  84053. if (!impostor) {
  84054. continue;
  84055. }
  84056. if (impostor.isDisposed) {
  84057. this.hideImpostor(this._impostors[i--]);
  84058. }
  84059. else {
  84060. var mesh = this._meshes[i];
  84061. if (mesh && plugin) {
  84062. plugin.syncMeshWithImpostor(mesh, impostor);
  84063. }
  84064. }
  84065. }
  84066. };
  84067. PhysicsViewer.prototype.showImpostor = function (impostor) {
  84068. if (!this._scene) {
  84069. return;
  84070. }
  84071. for (var i = 0; i < this._numMeshes; i++) {
  84072. if (this._impostors[i] == impostor) {
  84073. return;
  84074. }
  84075. }
  84076. var debugMesh = this._getDebugMesh(impostor, this._scene);
  84077. if (debugMesh) {
  84078. this._impostors[this._numMeshes] = impostor;
  84079. this._meshes[this._numMeshes] = debugMesh;
  84080. if (this._numMeshes === 0) {
  84081. this._renderFunction = this._updateDebugMeshes.bind(this);
  84082. this._scene.registerBeforeRender(this._renderFunction);
  84083. }
  84084. this._numMeshes++;
  84085. }
  84086. };
  84087. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  84088. if (!impostor || !this._scene) {
  84089. return;
  84090. }
  84091. var removed = false;
  84092. for (var i = 0; i < this._numMeshes; i++) {
  84093. if (this._impostors[i] == impostor) {
  84094. var mesh = this._meshes[i];
  84095. if (!mesh) {
  84096. continue;
  84097. }
  84098. this._scene.removeMesh(mesh);
  84099. mesh.dispose();
  84100. this._numMeshes--;
  84101. if (this._numMeshes > 0) {
  84102. this._meshes[i] = this._meshes[this._numMeshes];
  84103. this._impostors[i] = this._impostors[this._numMeshes];
  84104. this._meshes[this._numMeshes] = null;
  84105. this._impostors[this._numMeshes] = null;
  84106. }
  84107. else {
  84108. this._meshes[0] = null;
  84109. this._impostors[0] = null;
  84110. }
  84111. removed = true;
  84112. break;
  84113. }
  84114. }
  84115. if (removed && this._numMeshes === 0) {
  84116. this._scene.unregisterBeforeRender(this._renderFunction);
  84117. }
  84118. };
  84119. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  84120. if (!this._debugMaterial) {
  84121. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  84122. this._debugMaterial.wireframe = true;
  84123. }
  84124. return this._debugMaterial;
  84125. };
  84126. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  84127. if (!this._debugBoxMesh) {
  84128. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  84129. this._debugBoxMesh.renderingGroupId = 1;
  84130. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84131. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  84132. scene.removeMesh(this._debugBoxMesh);
  84133. }
  84134. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  84135. };
  84136. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  84137. if (!this._debugSphereMesh) {
  84138. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  84139. this._debugSphereMesh.renderingGroupId = 1;
  84140. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84141. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  84142. scene.removeMesh(this._debugSphereMesh);
  84143. }
  84144. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  84145. };
  84146. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  84147. var mesh = null;
  84148. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  84149. mesh = this._getDebugBoxMesh(scene);
  84150. impostor.getBoxSizeToRef(mesh.scaling);
  84151. }
  84152. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  84153. mesh = this._getDebugSphereMesh(scene);
  84154. var radius = impostor.getRadius();
  84155. mesh.scaling.x = radius * 2;
  84156. mesh.scaling.y = radius * 2;
  84157. mesh.scaling.z = radius * 2;
  84158. }
  84159. return mesh;
  84160. };
  84161. PhysicsViewer.prototype.dispose = function () {
  84162. for (var i = 0; i < this._numMeshes; i++) {
  84163. this.hideImpostor(this._impostors[i]);
  84164. }
  84165. if (this._debugBoxMesh) {
  84166. this._debugBoxMesh.dispose();
  84167. }
  84168. if (this._debugSphereMesh) {
  84169. this._debugSphereMesh.dispose();
  84170. }
  84171. if (this._debugMaterial) {
  84172. this._debugMaterial.dispose();
  84173. }
  84174. this._impostors.length = 0;
  84175. this._scene = null;
  84176. this._physicsEnginePlugin = null;
  84177. };
  84178. return PhysicsViewer;
  84179. }());
  84180. Debug.PhysicsViewer = PhysicsViewer;
  84181. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84182. })(BABYLON || (BABYLON = {}));
  84183. //# sourceMappingURL=babylon.physicsViewer.js.map
  84184. "use strict";
  84185. var BABYLON;
  84186. (function (BABYLON) {
  84187. var BoundingBoxRenderer = /** @class */ (function () {
  84188. function BoundingBoxRenderer(scene) {
  84189. this.frontColor = new BABYLON.Color3(1, 1, 1);
  84190. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  84191. this.showBackLines = true;
  84192. this.renderList = new BABYLON.SmartArray(32);
  84193. this._vertexBuffers = {};
  84194. this._scene = scene;
  84195. }
  84196. BoundingBoxRenderer.prototype._prepareRessources = function () {
  84197. if (this._colorShader) {
  84198. return;
  84199. }
  84200. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  84201. attributes: [BABYLON.VertexBuffer.PositionKind],
  84202. uniforms: ["world", "viewProjection", "color"]
  84203. });
  84204. var engine = this._scene.getEngine();
  84205. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84207. this._createIndexBuffer();
  84208. };
  84209. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84210. var engine = this._scene.getEngine();
  84211. 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]);
  84212. };
  84213. BoundingBoxRenderer.prototype._rebuild = function () {
  84214. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84215. if (vb) {
  84216. vb._rebuild();
  84217. }
  84218. this._createIndexBuffer();
  84219. };
  84220. BoundingBoxRenderer.prototype.reset = function () {
  84221. this.renderList.reset();
  84222. };
  84223. BoundingBoxRenderer.prototype.render = function () {
  84224. if (this.renderList.length === 0) {
  84225. return;
  84226. }
  84227. this._prepareRessources();
  84228. if (!this._colorShader.isReady()) {
  84229. return;
  84230. }
  84231. var engine = this._scene.getEngine();
  84232. engine.setDepthWrite(false);
  84233. this._colorShader._preBind();
  84234. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84235. var boundingBox = this.renderList.data[boundingBoxIndex];
  84236. var min = boundingBox.minimum;
  84237. var max = boundingBox.maximum;
  84238. var diff = max.subtract(min);
  84239. var median = min.add(diff.scale(0.5));
  84240. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84241. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84242. .multiply(boundingBox.getWorldMatrix());
  84243. // VBOs
  84244. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84245. if (this.showBackLines) {
  84246. // Back
  84247. engine.setDepthFunctionToGreaterOrEqual();
  84248. this._scene.resetCachedMaterial();
  84249. this._colorShader.setColor4("color", this.backColor.toColor4());
  84250. this._colorShader.bind(worldMatrix);
  84251. // Draw order
  84252. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84253. }
  84254. // Front
  84255. engine.setDepthFunctionToLess();
  84256. this._scene.resetCachedMaterial();
  84257. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84258. this._colorShader.bind(worldMatrix);
  84259. // Draw order
  84260. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84261. }
  84262. this._colorShader.unbind();
  84263. engine.setDepthFunctionToLessOrEqual();
  84264. engine.setDepthWrite(true);
  84265. };
  84266. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84267. this._prepareRessources();
  84268. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84269. return;
  84270. }
  84271. var engine = this._scene.getEngine();
  84272. engine.setDepthWrite(false);
  84273. engine.setColorWrite(false);
  84274. this._colorShader._preBind();
  84275. var boundingBox = mesh._boundingInfo.boundingBox;
  84276. var min = boundingBox.minimum;
  84277. var max = boundingBox.maximum;
  84278. var diff = max.subtract(min);
  84279. var median = min.add(diff.scale(0.5));
  84280. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84281. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84282. .multiply(boundingBox.getWorldMatrix());
  84283. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84284. engine.setDepthFunctionToLess();
  84285. this._scene.resetCachedMaterial();
  84286. this._colorShader.bind(worldMatrix);
  84287. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84288. this._colorShader.unbind();
  84289. engine.setDepthFunctionToLessOrEqual();
  84290. engine.setDepthWrite(true);
  84291. engine.setColorWrite(true);
  84292. };
  84293. BoundingBoxRenderer.prototype.dispose = function () {
  84294. if (!this._colorShader) {
  84295. return;
  84296. }
  84297. this.renderList.dispose();
  84298. this._colorShader.dispose();
  84299. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84300. if (buffer) {
  84301. buffer.dispose();
  84302. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84303. }
  84304. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84305. };
  84306. return BoundingBoxRenderer;
  84307. }());
  84308. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  84309. })(BABYLON || (BABYLON = {}));
  84310. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  84311. "use strict";
  84312. var BABYLON;
  84313. (function (BABYLON) {
  84314. /**
  84315. * Defines a target to use with MorphTargetManager
  84316. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84317. */
  84318. var MorphTarget = /** @class */ (function () {
  84319. /**
  84320. * Creates a new MorphTarget
  84321. * @param name defines the name of the target
  84322. * @param influence defines the influence to use
  84323. */
  84324. function MorphTarget(
  84325. /** defines the name of the target */
  84326. name, influence) {
  84327. if (influence === void 0) { influence = 0; }
  84328. this.name = name;
  84329. /**
  84330. * Gets or sets the list of animations
  84331. */
  84332. this.animations = new Array();
  84333. this._positions = null;
  84334. this._normals = null;
  84335. this._tangents = null;
  84336. /**
  84337. * Observable raised when the influence changes
  84338. */
  84339. this.onInfluenceChanged = new BABYLON.Observable();
  84340. this.influence = influence;
  84341. }
  84342. Object.defineProperty(MorphTarget.prototype, "influence", {
  84343. /**
  84344. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  84345. */
  84346. get: function () {
  84347. return this._influence;
  84348. },
  84349. set: function (influence) {
  84350. if (this._influence === influence) {
  84351. return;
  84352. }
  84353. var previous = this._influence;
  84354. this._influence = influence;
  84355. if (this.onInfluenceChanged.hasObservers) {
  84356. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  84357. }
  84358. },
  84359. enumerable: true,
  84360. configurable: true
  84361. });
  84362. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  84363. /**
  84364. * Gets a boolean defining if the target contains position data
  84365. */
  84366. get: function () {
  84367. return !!this._positions;
  84368. },
  84369. enumerable: true,
  84370. configurable: true
  84371. });
  84372. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  84373. /**
  84374. * Gets a boolean defining if the target contains normal data
  84375. */
  84376. get: function () {
  84377. return !!this._normals;
  84378. },
  84379. enumerable: true,
  84380. configurable: true
  84381. });
  84382. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  84383. /**
  84384. * Gets a boolean defining if the target contains tangent data
  84385. */
  84386. get: function () {
  84387. return !!this._tangents;
  84388. },
  84389. enumerable: true,
  84390. configurable: true
  84391. });
  84392. /**
  84393. * Affects position data to this target
  84394. * @param data defines the position data to use
  84395. */
  84396. MorphTarget.prototype.setPositions = function (data) {
  84397. this._positions = data;
  84398. };
  84399. /**
  84400. * Gets the position data stored in this target
  84401. * @returns a FloatArray containing the position data (or null if not present)
  84402. */
  84403. MorphTarget.prototype.getPositions = function () {
  84404. return this._positions;
  84405. };
  84406. /**
  84407. * Affects normal data to this target
  84408. * @param data defines the normal data to use
  84409. */
  84410. MorphTarget.prototype.setNormals = function (data) {
  84411. this._normals = data;
  84412. };
  84413. /**
  84414. * Gets the normal data stored in this target
  84415. * @returns a FloatArray containing the normal data (or null if not present)
  84416. */
  84417. MorphTarget.prototype.getNormals = function () {
  84418. return this._normals;
  84419. };
  84420. /**
  84421. * Affects tangent data to this target
  84422. * @param data defines the tangent data to use
  84423. */
  84424. MorphTarget.prototype.setTangents = function (data) {
  84425. this._tangents = data;
  84426. };
  84427. /**
  84428. * Gets the tangent data stored in this target
  84429. * @returns a FloatArray containing the tangent data (or null if not present)
  84430. */
  84431. MorphTarget.prototype.getTangents = function () {
  84432. return this._tangents;
  84433. };
  84434. /**
  84435. * Serializes the current target into a Serialization object
  84436. * @returns the serialized object
  84437. */
  84438. MorphTarget.prototype.serialize = function () {
  84439. var serializationObject = {};
  84440. serializationObject.name = this.name;
  84441. serializationObject.influence = this.influence;
  84442. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  84443. if (this.hasNormals) {
  84444. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  84445. }
  84446. if (this.hasTangents) {
  84447. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  84448. }
  84449. // Animations
  84450. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  84451. return serializationObject;
  84452. };
  84453. // Statics
  84454. /**
  84455. * Creates a new target from serialized data
  84456. * @param serializationObject defines the serialized data to use
  84457. * @returns a new MorphTarget
  84458. */
  84459. MorphTarget.Parse = function (serializationObject) {
  84460. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  84461. result.setPositions(serializationObject.positions);
  84462. if (serializationObject.normals) {
  84463. result.setNormals(serializationObject.normals);
  84464. }
  84465. if (serializationObject.tangents) {
  84466. result.setTangents(serializationObject.tangents);
  84467. }
  84468. // Animations
  84469. if (serializationObject.animations) {
  84470. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  84471. var parsedAnimation = serializationObject.animations[animationIndex];
  84472. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  84473. }
  84474. }
  84475. return result;
  84476. };
  84477. /**
  84478. * Creates a MorphTarget from mesh data
  84479. * @param mesh defines the source mesh
  84480. * @param name defines the name to use for the new target
  84481. * @param influence defines the influence to attach to the target
  84482. * @returns a new MorphTarget
  84483. */
  84484. MorphTarget.FromMesh = function (mesh, name, influence) {
  84485. if (!name) {
  84486. name = mesh.name;
  84487. }
  84488. var result = new MorphTarget(name, influence);
  84489. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  84491. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  84492. }
  84493. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  84494. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  84495. }
  84496. return result;
  84497. };
  84498. return MorphTarget;
  84499. }());
  84500. BABYLON.MorphTarget = MorphTarget;
  84501. })(BABYLON || (BABYLON = {}));
  84502. //# sourceMappingURL=babylon.morphTarget.js.map
  84503. "use strict";
  84504. var BABYLON;
  84505. (function (BABYLON) {
  84506. /**
  84507. * This class is used to deform meshes using morphing between different targets
  84508. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84509. */
  84510. var MorphTargetManager = /** @class */ (function () {
  84511. /**
  84512. * Creates a new MorphTargetManager
  84513. * @param scene defines the current scene
  84514. */
  84515. function MorphTargetManager(scene) {
  84516. if (scene === void 0) { scene = null; }
  84517. this._targets = new Array();
  84518. this._targetObservable = new Array();
  84519. this._activeTargets = new BABYLON.SmartArray(16);
  84520. this._supportsNormals = false;
  84521. this._supportsTangents = false;
  84522. this._vertexCount = 0;
  84523. this._uniqueId = 0;
  84524. this._tempInfluences = new Array();
  84525. if (!scene) {
  84526. scene = BABYLON.Engine.LastCreatedScene;
  84527. }
  84528. this._scene = scene;
  84529. if (this._scene) {
  84530. this._scene.morphTargetManagers.push(this);
  84531. this._uniqueId = this._scene.getUniqueId();
  84532. }
  84533. }
  84534. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  84535. /**
  84536. * Gets the unique ID of this manager
  84537. */
  84538. get: function () {
  84539. return this._uniqueId;
  84540. },
  84541. enumerable: true,
  84542. configurable: true
  84543. });
  84544. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  84545. /**
  84546. * Gets the number of vertices handled by this manager
  84547. */
  84548. get: function () {
  84549. return this._vertexCount;
  84550. },
  84551. enumerable: true,
  84552. configurable: true
  84553. });
  84554. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  84555. /**
  84556. * Gets a boolean indicating if this manager supports morphing of normals
  84557. */
  84558. get: function () {
  84559. return this._supportsNormals;
  84560. },
  84561. enumerable: true,
  84562. configurable: true
  84563. });
  84564. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  84565. /**
  84566. * Gets a boolean indicating if this manager supports morphing of tangents
  84567. */
  84568. get: function () {
  84569. return this._supportsTangents;
  84570. },
  84571. enumerable: true,
  84572. configurable: true
  84573. });
  84574. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  84575. /**
  84576. * Gets the number of targets stored in this manager
  84577. */
  84578. get: function () {
  84579. return this._targets.length;
  84580. },
  84581. enumerable: true,
  84582. configurable: true
  84583. });
  84584. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  84585. /**
  84586. * Gets the number of influencers (ie. the number of targets with influences > 0)
  84587. */
  84588. get: function () {
  84589. return this._activeTargets.length;
  84590. },
  84591. enumerable: true,
  84592. configurable: true
  84593. });
  84594. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  84595. /**
  84596. * Gets the list of influences (one per target)
  84597. */
  84598. get: function () {
  84599. return this._influences;
  84600. },
  84601. enumerable: true,
  84602. configurable: true
  84603. });
  84604. /**
  84605. * Gets the active target at specified index. An active target is a target with an influence > 0
  84606. * @param index defines the index to check
  84607. * @returns the requested target
  84608. */
  84609. MorphTargetManager.prototype.getActiveTarget = function (index) {
  84610. return this._activeTargets.data[index];
  84611. };
  84612. /**
  84613. * Gets the target at specified index
  84614. * @param index defines the index to check
  84615. * @returns the requested target
  84616. */
  84617. MorphTargetManager.prototype.getTarget = function (index) {
  84618. return this._targets[index];
  84619. };
  84620. /**
  84621. * Add a new target to this manager
  84622. * @param target defines the target to add
  84623. */
  84624. MorphTargetManager.prototype.addTarget = function (target) {
  84625. var _this = this;
  84626. this._targets.push(target);
  84627. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  84628. _this._syncActiveTargets(needUpdate);
  84629. }));
  84630. this._syncActiveTargets(true);
  84631. };
  84632. /**
  84633. * Removes a target from the manager
  84634. * @param target defines the target to remove
  84635. */
  84636. MorphTargetManager.prototype.removeTarget = function (target) {
  84637. var index = this._targets.indexOf(target);
  84638. if (index >= 0) {
  84639. this._targets.splice(index, 1);
  84640. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  84641. this._syncActiveTargets(true);
  84642. }
  84643. };
  84644. /**
  84645. * Serializes the current manager into a Serialization object
  84646. * @returns the serialized object
  84647. */
  84648. MorphTargetManager.prototype.serialize = function () {
  84649. var serializationObject = {};
  84650. serializationObject.id = this.uniqueId;
  84651. serializationObject.targets = [];
  84652. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84653. var target = _a[_i];
  84654. serializationObject.targets.push(target.serialize());
  84655. }
  84656. return serializationObject;
  84657. };
  84658. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  84659. var influenceCount = 0;
  84660. this._activeTargets.reset();
  84661. this._supportsNormals = true;
  84662. this._supportsTangents = true;
  84663. this._vertexCount = 0;
  84664. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  84665. var target = _a[_i];
  84666. this._activeTargets.push(target);
  84667. this._tempInfluences[influenceCount++] = target.influence;
  84668. var positions = target.getPositions();
  84669. if (positions) {
  84670. this._supportsNormals = this._supportsNormals && target.hasNormals;
  84671. this._supportsTangents = this._supportsTangents && target.hasTangents;
  84672. var vertexCount = positions.length / 3;
  84673. if (this._vertexCount === 0) {
  84674. this._vertexCount = vertexCount;
  84675. }
  84676. else if (this._vertexCount !== vertexCount) {
  84677. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  84678. return;
  84679. }
  84680. }
  84681. }
  84682. if (!this._influences || this._influences.length !== influenceCount) {
  84683. this._influences = new Float32Array(influenceCount);
  84684. }
  84685. for (var index = 0; index < influenceCount; index++) {
  84686. this._influences[index] = this._tempInfluences[index];
  84687. }
  84688. if (needUpdate) {
  84689. this.synchronize();
  84690. }
  84691. };
  84692. /**
  84693. * Syncrhonize the targets with all the meshes using this morph target manager
  84694. */
  84695. MorphTargetManager.prototype.synchronize = function () {
  84696. if (!this._scene) {
  84697. return;
  84698. }
  84699. // Flag meshes as dirty to resync with the active targets
  84700. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  84701. var mesh = _a[_i];
  84702. if (mesh.morphTargetManager === this) {
  84703. mesh._syncGeometryWithMorphTargetManager();
  84704. }
  84705. }
  84706. };
  84707. // Statics
  84708. /**
  84709. * Creates a new MorphTargetManager from serialized data
  84710. * @param serializationObject defines the serialized data
  84711. * @param scene defines the hosting scene
  84712. * @returns the new MorphTargetManager
  84713. */
  84714. MorphTargetManager.Parse = function (serializationObject, scene) {
  84715. var result = new MorphTargetManager(scene);
  84716. result._uniqueId = serializationObject.id;
  84717. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  84718. var targetData = _a[_i];
  84719. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  84720. }
  84721. return result;
  84722. };
  84723. return MorphTargetManager;
  84724. }());
  84725. BABYLON.MorphTargetManager = MorphTargetManager;
  84726. })(BABYLON || (BABYLON = {}));
  84727. //# sourceMappingURL=babylon.morphTargetManager.js.map
  84728. "use strict";
  84729. var BABYLON;
  84730. (function (BABYLON) {
  84731. var Octree = /** @class */ (function () {
  84732. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  84733. if (maxDepth === void 0) { maxDepth = 2; }
  84734. this.maxDepth = maxDepth;
  84735. this.dynamicContent = new Array();
  84736. this._maxBlockCapacity = maxBlockCapacity || 64;
  84737. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  84738. this._creationFunc = creationFunc;
  84739. }
  84740. // Methods
  84741. Octree.prototype.update = function (worldMin, worldMax, entries) {
  84742. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  84743. };
  84744. Octree.prototype.addMesh = function (entry) {
  84745. for (var index = 0; index < this.blocks.length; index++) {
  84746. var block = this.blocks[index];
  84747. block.addEntry(entry);
  84748. }
  84749. };
  84750. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  84751. this._selectionContent.reset();
  84752. for (var index = 0; index < this.blocks.length; index++) {
  84753. var block = this.blocks[index];
  84754. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  84755. }
  84756. if (allowDuplicate) {
  84757. this._selectionContent.concat(this.dynamicContent);
  84758. }
  84759. else {
  84760. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84761. }
  84762. return this._selectionContent;
  84763. };
  84764. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  84765. this._selectionContent.reset();
  84766. for (var index = 0; index < this.blocks.length; index++) {
  84767. var block = this.blocks[index];
  84768. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  84769. }
  84770. if (allowDuplicate) {
  84771. this._selectionContent.concat(this.dynamicContent);
  84772. }
  84773. else {
  84774. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84775. }
  84776. return this._selectionContent;
  84777. };
  84778. Octree.prototype.intersectsRay = function (ray) {
  84779. this._selectionContent.reset();
  84780. for (var index = 0; index < this.blocks.length; index++) {
  84781. var block = this.blocks[index];
  84782. block.intersectsRay(ray, this._selectionContent);
  84783. }
  84784. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84785. return this._selectionContent;
  84786. };
  84787. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  84788. target.blocks = new Array();
  84789. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  84790. // Segmenting space
  84791. for (var x = 0; x < 2; x++) {
  84792. for (var y = 0; y < 2; y++) {
  84793. for (var z = 0; z < 2; z++) {
  84794. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  84795. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  84796. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  84797. block.addEntries(entries);
  84798. target.blocks.push(block);
  84799. }
  84800. }
  84801. }
  84802. };
  84803. Octree.CreationFuncForMeshes = function (entry, block) {
  84804. var boundingInfo = entry.getBoundingInfo();
  84805. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84806. block.entries.push(entry);
  84807. }
  84808. };
  84809. Octree.CreationFuncForSubMeshes = function (entry, block) {
  84810. var boundingInfo = entry.getBoundingInfo();
  84811. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84812. block.entries.push(entry);
  84813. }
  84814. };
  84815. return Octree;
  84816. }());
  84817. BABYLON.Octree = Octree;
  84818. })(BABYLON || (BABYLON = {}));
  84819. //# sourceMappingURL=babylon.octree.js.map
  84820. "use strict";
  84821. var BABYLON;
  84822. (function (BABYLON) {
  84823. var OctreeBlock = /** @class */ (function () {
  84824. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  84825. this.entries = new Array();
  84826. this._boundingVectors = new Array();
  84827. this._capacity = capacity;
  84828. this._depth = depth;
  84829. this._maxDepth = maxDepth;
  84830. this._creationFunc = creationFunc;
  84831. this._minPoint = minPoint;
  84832. this._maxPoint = maxPoint;
  84833. this._boundingVectors.push(minPoint.clone());
  84834. this._boundingVectors.push(maxPoint.clone());
  84835. this._boundingVectors.push(minPoint.clone());
  84836. this._boundingVectors[2].x = maxPoint.x;
  84837. this._boundingVectors.push(minPoint.clone());
  84838. this._boundingVectors[3].y = maxPoint.y;
  84839. this._boundingVectors.push(minPoint.clone());
  84840. this._boundingVectors[4].z = maxPoint.z;
  84841. this._boundingVectors.push(maxPoint.clone());
  84842. this._boundingVectors[5].z = minPoint.z;
  84843. this._boundingVectors.push(maxPoint.clone());
  84844. this._boundingVectors[6].x = minPoint.x;
  84845. this._boundingVectors.push(maxPoint.clone());
  84846. this._boundingVectors[7].y = minPoint.y;
  84847. }
  84848. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  84849. // Property
  84850. get: function () {
  84851. return this._capacity;
  84852. },
  84853. enumerable: true,
  84854. configurable: true
  84855. });
  84856. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  84857. get: function () {
  84858. return this._minPoint;
  84859. },
  84860. enumerable: true,
  84861. configurable: true
  84862. });
  84863. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  84864. get: function () {
  84865. return this._maxPoint;
  84866. },
  84867. enumerable: true,
  84868. configurable: true
  84869. });
  84870. // Methods
  84871. OctreeBlock.prototype.addEntry = function (entry) {
  84872. if (this.blocks) {
  84873. for (var index = 0; index < this.blocks.length; index++) {
  84874. var block = this.blocks[index];
  84875. block.addEntry(entry);
  84876. }
  84877. return;
  84878. }
  84879. this._creationFunc(entry, this);
  84880. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  84881. this.createInnerBlocks();
  84882. }
  84883. };
  84884. OctreeBlock.prototype.addEntries = function (entries) {
  84885. for (var index = 0; index < entries.length; index++) {
  84886. var mesh = entries[index];
  84887. this.addEntry(mesh);
  84888. }
  84889. };
  84890. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  84891. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  84892. if (this.blocks) {
  84893. for (var index = 0; index < this.blocks.length; index++) {
  84894. var block = this.blocks[index];
  84895. block.select(frustumPlanes, selection, allowDuplicate);
  84896. }
  84897. return;
  84898. }
  84899. if (allowDuplicate) {
  84900. selection.concat(this.entries);
  84901. }
  84902. else {
  84903. selection.concatWithNoDuplicate(this.entries);
  84904. }
  84905. }
  84906. };
  84907. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  84908. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  84909. if (this.blocks) {
  84910. for (var index = 0; index < this.blocks.length; index++) {
  84911. var block = this.blocks[index];
  84912. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  84913. }
  84914. return;
  84915. }
  84916. if (allowDuplicate) {
  84917. selection.concat(this.entries);
  84918. }
  84919. else {
  84920. selection.concatWithNoDuplicate(this.entries);
  84921. }
  84922. }
  84923. };
  84924. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  84925. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  84926. if (this.blocks) {
  84927. for (var index = 0; index < this.blocks.length; index++) {
  84928. var block = this.blocks[index];
  84929. block.intersectsRay(ray, selection);
  84930. }
  84931. return;
  84932. }
  84933. selection.concatWithNoDuplicate(this.entries);
  84934. }
  84935. };
  84936. OctreeBlock.prototype.createInnerBlocks = function () {
  84937. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  84938. };
  84939. return OctreeBlock;
  84940. }());
  84941. BABYLON.OctreeBlock = OctreeBlock;
  84942. })(BABYLON || (BABYLON = {}));
  84943. //# sourceMappingURL=babylon.octreeBlock.js.map
  84944. "use strict";
  84945. var BABYLON;
  84946. (function (BABYLON) {
  84947. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  84948. __extends(VRDistortionCorrectionPostProcess, _super);
  84949. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  84950. var _this = _super.call(this, name, "vrDistortionCorrection", [
  84951. 'LensCenter',
  84952. 'Scale',
  84953. 'ScaleIn',
  84954. 'HmdWarpParam'
  84955. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  84956. _this._isRightEye = isRightEye;
  84957. _this._distortionFactors = vrMetrics.distortionK;
  84958. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  84959. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  84960. _this.adaptScaleToCurrentViewport = true;
  84961. _this.onSizeChangedObservable.add(function () {
  84962. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  84963. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  84964. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  84965. });
  84966. _this.onApplyObservable.add(function (effect) {
  84967. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  84968. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  84969. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  84970. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  84971. });
  84972. return _this;
  84973. }
  84974. return VRDistortionCorrectionPostProcess;
  84975. }(BABYLON.PostProcess));
  84976. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  84977. })(BABYLON || (BABYLON = {}));
  84978. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  84979. "use strict";
  84980. var BABYLON;
  84981. (function (BABYLON) {
  84982. var AnaglyphPostProcess = /** @class */ (function (_super) {
  84983. __extends(AnaglyphPostProcess, _super);
  84984. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  84985. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  84986. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84987. _this.onApplyObservable.add(function (effect) {
  84988. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  84989. });
  84990. return _this;
  84991. }
  84992. return AnaglyphPostProcess;
  84993. }(BABYLON.PostProcess));
  84994. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  84995. })(BABYLON || (BABYLON = {}));
  84996. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  84997. "use strict";
  84998. var BABYLON;
  84999. (function (BABYLON) {
  85000. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  85001. __extends(StereoscopicInterlacePostProcess, _super);
  85002. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  85003. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  85004. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85005. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85006. _this.onSizeChangedObservable.add(function () {
  85007. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85008. });
  85009. _this.onApplyObservable.add(function (effect) {
  85010. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  85011. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  85012. });
  85013. return _this;
  85014. }
  85015. return StereoscopicInterlacePostProcess;
  85016. }(BABYLON.PostProcess));
  85017. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  85018. })(BABYLON || (BABYLON = {}));
  85019. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  85020. "use strict";
  85021. var BABYLON;
  85022. (function (BABYLON) {
  85023. /**
  85024. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  85025. * Screen rotation is taken into account.
  85026. */
  85027. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  85028. function FreeCameraDeviceOrientationInput() {
  85029. var _this = this;
  85030. this._screenOrientationAngle = 0;
  85031. this._screenQuaternion = new BABYLON.Quaternion();
  85032. this._alpha = 0;
  85033. this._beta = 0;
  85034. this._gamma = 0;
  85035. this._orientationChanged = function () {
  85036. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  85037. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  85038. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  85039. };
  85040. this._deviceOrientation = function (evt) {
  85041. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  85042. _this._beta = evt.beta !== null ? evt.beta : 0;
  85043. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  85044. };
  85045. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  85046. this._orientationChanged();
  85047. }
  85048. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  85049. get: function () {
  85050. return this._camera;
  85051. },
  85052. set: function (camera) {
  85053. this._camera = camera;
  85054. if (this._camera != null && !this._camera.rotationQuaternion) {
  85055. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  85056. }
  85057. },
  85058. enumerable: true,
  85059. configurable: true
  85060. });
  85061. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85062. window.addEventListener("orientationchange", this._orientationChanged);
  85063. window.addEventListener("deviceorientation", this._deviceOrientation);
  85064. //In certain cases, the attach control is called AFTER orientation was changed,
  85065. //So this is needed.
  85066. this._orientationChanged();
  85067. };
  85068. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  85069. window.removeEventListener("orientationchange", this._orientationChanged);
  85070. window.removeEventListener("deviceorientation", this._deviceOrientation);
  85071. };
  85072. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  85073. //if no device orientation provided, don't update the rotation.
  85074. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  85075. if (!this._alpha)
  85076. return;
  85077. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  85078. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  85079. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  85080. //Mirror on XY Plane
  85081. this._camera.rotationQuaternion.z *= -1;
  85082. this._camera.rotationQuaternion.w *= -1;
  85083. };
  85084. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  85085. return "FreeCameraDeviceOrientationInput";
  85086. };
  85087. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  85088. return "deviceOrientation";
  85089. };
  85090. return FreeCameraDeviceOrientationInput;
  85091. }());
  85092. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  85093. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  85094. })(BABYLON || (BABYLON = {}));
  85095. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  85096. "use strict";
  85097. var BABYLON;
  85098. (function (BABYLON) {
  85099. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  85100. function ArcRotateCameraVRDeviceOrientationInput() {
  85101. this.alphaCorrection = 1;
  85102. this.betaCorrection = 1;
  85103. this.gammaCorrection = 1;
  85104. this._alpha = 0;
  85105. this._gamma = 0;
  85106. this._dirty = false;
  85107. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  85108. }
  85109. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85110. this.camera.attachControl(element, noPreventDefault);
  85111. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  85112. };
  85113. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  85114. if (evt.alpha !== null) {
  85115. this._alpha = +evt.alpha | 0;
  85116. }
  85117. if (evt.gamma !== null) {
  85118. this._gamma = +evt.gamma | 0;
  85119. }
  85120. this._dirty = true;
  85121. };
  85122. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  85123. if (this._dirty) {
  85124. this._dirty = false;
  85125. if (this._gamma < 0) {
  85126. this._gamma = 180 + this._gamma;
  85127. }
  85128. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  85129. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  85130. }
  85131. };
  85132. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  85133. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  85134. };
  85135. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  85136. return "ArcRotateCameraVRDeviceOrientationInput";
  85137. };
  85138. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  85139. return "VRDeviceOrientation";
  85140. };
  85141. return ArcRotateCameraVRDeviceOrientationInput;
  85142. }());
  85143. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  85144. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  85145. })(BABYLON || (BABYLON = {}));
  85146. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  85147. "use strict";
  85148. var BABYLON;
  85149. (function (BABYLON) {
  85150. var VRCameraMetrics = /** @class */ (function () {
  85151. function VRCameraMetrics() {
  85152. this.compensateDistortion = true;
  85153. }
  85154. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  85155. get: function () {
  85156. return this.hResolution / (2 * this.vResolution);
  85157. },
  85158. enumerable: true,
  85159. configurable: true
  85160. });
  85161. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  85162. get: function () {
  85163. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  85164. },
  85165. enumerable: true,
  85166. configurable: true
  85167. });
  85168. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  85169. get: function () {
  85170. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85171. var h = (4 * meters) / this.hScreenSize;
  85172. return BABYLON.Matrix.Translation(h, 0, 0);
  85173. },
  85174. enumerable: true,
  85175. configurable: true
  85176. });
  85177. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  85178. get: function () {
  85179. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85180. var h = (4 * meters) / this.hScreenSize;
  85181. return BABYLON.Matrix.Translation(-h, 0, 0);
  85182. },
  85183. enumerable: true,
  85184. configurable: true
  85185. });
  85186. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  85187. get: function () {
  85188. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  85189. },
  85190. enumerable: true,
  85191. configurable: true
  85192. });
  85193. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  85194. get: function () {
  85195. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  85196. },
  85197. enumerable: true,
  85198. configurable: true
  85199. });
  85200. VRCameraMetrics.GetDefault = function () {
  85201. var result = new VRCameraMetrics();
  85202. result.hResolution = 1280;
  85203. result.vResolution = 800;
  85204. result.hScreenSize = 0.149759993;
  85205. result.vScreenSize = 0.0935999975;
  85206. result.vScreenCenter = 0.0467999987;
  85207. result.eyeToScreenDistance = 0.0410000011;
  85208. result.lensSeparationDistance = 0.0635000020;
  85209. result.interpupillaryDistance = 0.0640000030;
  85210. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85211. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85212. result.postProcessScaleFactor = 1.714605507808412;
  85213. result.lensCenterOffset = 0.151976421;
  85214. return result;
  85215. };
  85216. return VRCameraMetrics;
  85217. }());
  85218. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85219. })(BABYLON || (BABYLON = {}));
  85220. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85221. "use strict";
  85222. var BABYLON;
  85223. (function (BABYLON) {
  85224. /**
  85225. * This represents a WebVR camera.
  85226. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85227. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85228. */
  85229. var WebVRFreeCamera = /** @class */ (function (_super) {
  85230. __extends(WebVRFreeCamera, _super);
  85231. /**
  85232. * Instantiates a WebVRFreeCamera.
  85233. * @param name The name of the WebVRFreeCamera
  85234. * @param position The starting anchor position for the camera
  85235. * @param scene The scene the camera belongs to
  85236. * @param webVROptions a set of customizable options for the webVRCamera
  85237. */
  85238. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85239. if (webVROptions === void 0) { webVROptions = {}; }
  85240. var _this = _super.call(this, name, position, scene) || this;
  85241. _this.webVROptions = webVROptions;
  85242. /**
  85243. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85244. */
  85245. _this._vrDevice = null;
  85246. /**
  85247. * The rawPose of the vrDevice.
  85248. */
  85249. _this.rawPose = null;
  85250. _this._specsVersion = "1.1";
  85251. _this._attached = false;
  85252. _this._descendants = [];
  85253. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85254. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85255. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85256. _this._standingMatrix = null;
  85257. /**
  85258. * Represents device position in babylon space.
  85259. */
  85260. _this.devicePosition = BABYLON.Vector3.Zero();
  85261. /**
  85262. * Represents device rotation in babylon space.
  85263. */
  85264. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85265. /**
  85266. * The scale of the device to be used when translating from device space to babylon space.
  85267. */
  85268. _this.deviceScaleFactor = 1;
  85269. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85270. _this._worldToDevice = BABYLON.Matrix.Identity();
  85271. /**
  85272. * References to the webVR controllers for the vrDevice.
  85273. */
  85274. _this.controllers = [];
  85275. /**
  85276. * Emits an event when a controller is attached.
  85277. */
  85278. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85279. /**
  85280. * Emits an event when a controller's mesh has been loaded;
  85281. */
  85282. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85283. /**
  85284. * If the rig cameras be used as parent instead of this camera.
  85285. */
  85286. _this.rigParenting = true;
  85287. _this._defaultHeight = undefined;
  85288. _this._workingVector = BABYLON.Vector3.Zero();
  85289. _this._oneVector = BABYLON.Vector3.One();
  85290. _this._workingMatrix = BABYLON.Matrix.Identity();
  85291. _this._cache.position = BABYLON.Vector3.Zero();
  85292. if (webVROptions.defaultHeight) {
  85293. _this._defaultHeight = webVROptions.defaultHeight;
  85294. _this.position.y = _this._defaultHeight;
  85295. }
  85296. _this.minZ = 0.1;
  85297. //legacy support - the compensation boolean was removed.
  85298. if (arguments.length === 5) {
  85299. _this.webVROptions = arguments[4];
  85300. }
  85301. // default webVR options
  85302. if (_this.webVROptions.trackPosition == undefined) {
  85303. _this.webVROptions.trackPosition = true;
  85304. }
  85305. if (_this.webVROptions.controllerMeshes == undefined) {
  85306. _this.webVROptions.controllerMeshes = true;
  85307. }
  85308. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  85309. _this.webVROptions.defaultLightingOnControllers = true;
  85310. }
  85311. _this.rotationQuaternion = new BABYLON.Quaternion();
  85312. if (_this.webVROptions && _this.webVROptions.positionScale) {
  85313. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  85314. }
  85315. //enable VR
  85316. var engine = _this.getEngine();
  85317. _this._onVREnabled = function (success) { if (success) {
  85318. _this.initControllers();
  85319. } };
  85320. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  85321. engine.initWebVR().add(function (event) {
  85322. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  85323. return;
  85324. }
  85325. _this._vrDevice = event.vrDisplay;
  85326. //reset the rig parameters.
  85327. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  85328. if (_this._attached) {
  85329. _this.getEngine().enableVR();
  85330. }
  85331. });
  85332. if (typeof (VRFrameData) !== "undefined")
  85333. _this._frameData = new VRFrameData();
  85334. /**
  85335. * The idea behind the following lines:
  85336. * objects that have the camera as parent should actually have the rig cameras as a parent.
  85337. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  85338. * the second will not show it correctly.
  85339. *
  85340. * To solve this - each object that has the camera as parent will be added to a protected array.
  85341. * When the rig camera renders, it will take this array and set all of those to be its children.
  85342. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  85343. * Amazing!
  85344. */
  85345. scene.onBeforeCameraRenderObservable.add(function (camera) {
  85346. if (camera.parent === _this && _this.rigParenting) {
  85347. _this._descendants = _this.getDescendants(true, function (n) {
  85348. // don't take the cameras or the controllers!
  85349. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  85350. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  85351. return !isController && !isRigCamera;
  85352. });
  85353. _this._descendants.forEach(function (node) {
  85354. node.parent = camera;
  85355. });
  85356. }
  85357. });
  85358. scene.onAfterCameraRenderObservable.add(function (camera) {
  85359. if (camera.parent === _this && _this.rigParenting) {
  85360. _this._descendants.forEach(function (node) {
  85361. node.parent = _this;
  85362. });
  85363. }
  85364. });
  85365. return _this;
  85366. }
  85367. /**
  85368. * Gets the device distance from the ground in meters.
  85369. * @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.
  85370. */
  85371. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  85372. if (this._standingMatrix) {
  85373. // Add standing matrix offset to get real offset from ground in room
  85374. this._standingMatrix.getTranslationToRef(this._workingVector);
  85375. return this._deviceRoomPosition.y + this._workingVector.y;
  85376. }
  85377. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  85378. return this._defaultHeight || 0;
  85379. };
  85380. /**
  85381. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85382. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  85383. */
  85384. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  85385. var _this = this;
  85386. if (callback === void 0) { callback = function (bool) { }; }
  85387. // Use standing matrix if available
  85388. this.getEngine().initWebVRAsync().then(function (result) {
  85389. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  85390. callback(false);
  85391. }
  85392. else {
  85393. _this._standingMatrix = new BABYLON.Matrix();
  85394. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  85395. if (!_this.getScene().useRightHandedSystem) {
  85396. [2, 6, 8, 9, 14].forEach(function (num) {
  85397. if (_this._standingMatrix) {
  85398. _this._standingMatrix.m[num] *= -1;
  85399. }
  85400. });
  85401. }
  85402. callback(true);
  85403. }
  85404. });
  85405. };
  85406. /**
  85407. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85408. * @returns A promise with a boolean set to if the standing matrix is supported.
  85409. */
  85410. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  85411. var _this = this;
  85412. return new Promise(function (res, rej) {
  85413. _this.useStandingMatrix(function (supported) {
  85414. res(supported);
  85415. });
  85416. });
  85417. };
  85418. /**
  85419. * Disposes the camera
  85420. */
  85421. WebVRFreeCamera.prototype.dispose = function () {
  85422. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  85423. _super.prototype.dispose.call(this);
  85424. };
  85425. /**
  85426. * Gets a vrController by name.
  85427. * @param name The name of the controller to retreive
  85428. * @returns the controller matching the name specified or null if not found
  85429. */
  85430. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  85431. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  85432. var gp = _a[_i];
  85433. if (gp.hand === name) {
  85434. return gp;
  85435. }
  85436. }
  85437. return null;
  85438. };
  85439. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  85440. /**
  85441. * The controller corrisponding to the users left hand.
  85442. */
  85443. get: function () {
  85444. if (!this._leftController) {
  85445. this._leftController = this.getControllerByName("left");
  85446. }
  85447. return this._leftController;
  85448. },
  85449. enumerable: true,
  85450. configurable: true
  85451. });
  85452. ;
  85453. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  85454. /**
  85455. * The controller corrisponding to the users right hand.
  85456. */
  85457. get: function () {
  85458. if (!this._rightController) {
  85459. this._rightController = this.getControllerByName("right");
  85460. }
  85461. return this._rightController;
  85462. },
  85463. enumerable: true,
  85464. configurable: true
  85465. });
  85466. ;
  85467. /**
  85468. * Casts a ray forward from the vrCamera's gaze.
  85469. * @param length Length of the ray (default: 100)
  85470. * @returns the ray corrisponding to the gaze
  85471. */
  85472. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  85473. if (length === void 0) { length = 100; }
  85474. if (this.leftCamera) {
  85475. // Use left eye to avoid computation to compute center on every call
  85476. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  85477. }
  85478. else {
  85479. return _super.prototype.getForwardRay.call(this, length);
  85480. }
  85481. };
  85482. /**
  85483. * Updates the camera based on device's frame data
  85484. */
  85485. WebVRFreeCamera.prototype._checkInputs = function () {
  85486. if (this._vrDevice && this._vrDevice.isPresenting) {
  85487. this._vrDevice.getFrameData(this._frameData);
  85488. this.updateFromDevice(this._frameData.pose);
  85489. }
  85490. _super.prototype._checkInputs.call(this);
  85491. };
  85492. /**
  85493. * Updates the poseControlled values based on the input device pose.
  85494. * @param poseData Pose coming from the device
  85495. */
  85496. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  85497. if (poseData && poseData.orientation) {
  85498. this.rawPose = poseData;
  85499. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  85500. if (this.getScene().useRightHandedSystem) {
  85501. this._deviceRoomRotationQuaternion.z *= -1;
  85502. this._deviceRoomRotationQuaternion.w *= -1;
  85503. }
  85504. if (this.webVROptions.trackPosition && this.rawPose.position) {
  85505. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  85506. if (this.getScene().useRightHandedSystem) {
  85507. this._deviceRoomPosition.z *= -1;
  85508. }
  85509. }
  85510. }
  85511. };
  85512. /**
  85513. * WebVR's attach control will start broadcasting frames to the device.
  85514. * Note that in certain browsers (chrome for example) this function must be called
  85515. * within a user-interaction callback. Example:
  85516. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  85517. *
  85518. * @param element html element to attach the vrDevice to
  85519. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  85520. */
  85521. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  85522. _super.prototype.attachControl.call(this, element, noPreventDefault);
  85523. this._attached = true;
  85524. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  85525. if (this._vrDevice) {
  85526. this.getEngine().enableVR();
  85527. }
  85528. };
  85529. /**
  85530. * Detaches the camera from the html element and disables VR
  85531. *
  85532. * @param element html element to detach from
  85533. */
  85534. WebVRFreeCamera.prototype.detachControl = function (element) {
  85535. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  85536. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  85537. _super.prototype.detachControl.call(this, element);
  85538. this._attached = false;
  85539. this.getEngine().disableVR();
  85540. };
  85541. /**
  85542. * @returns the name of this class
  85543. */
  85544. WebVRFreeCamera.prototype.getClassName = function () {
  85545. return "WebVRFreeCamera";
  85546. };
  85547. /**
  85548. * Calls resetPose on the vrDisplay
  85549. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  85550. */
  85551. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  85552. //uses the vrDisplay's "resetPose()".
  85553. //pitch and roll won't be affected.
  85554. this._vrDevice.resetPose();
  85555. };
  85556. /**
  85557. * Updates the rig cameras (left and right eye)
  85558. */
  85559. WebVRFreeCamera.prototype._updateRigCameras = function () {
  85560. var camLeft = this._rigCameras[0];
  85561. var camRight = this._rigCameras[1];
  85562. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85563. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  85564. camLeft.position.copyFrom(this._deviceRoomPosition);
  85565. camRight.position.copyFrom(this._deviceRoomPosition);
  85566. };
  85567. /**
  85568. * Updates the cached values of the camera
  85569. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  85570. */
  85571. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  85572. var _this = this;
  85573. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  85574. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  85575. if (!this.updateCacheCalled) {
  85576. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  85577. this.updateCacheCalled = true;
  85578. this.update();
  85579. }
  85580. // Set working vector to the device position in room space rotated by the new rotation
  85581. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  85582. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  85583. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  85584. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  85585. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  85586. // Add translation from anchor position
  85587. this._deviceToWorld.getTranslationToRef(this._workingVector);
  85588. this._workingVector.addInPlace(this.position);
  85589. this._workingVector.subtractInPlace(this._cache.position);
  85590. this._deviceToWorld.setTranslation(this._workingVector);
  85591. // Set an inverted matrix to be used when updating the camera
  85592. this._deviceToWorld.invertToRef(this._worldToDevice);
  85593. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  85594. this.controllers.forEach(function (controller) {
  85595. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  85596. controller.update();
  85597. });
  85598. }
  85599. if (!ignoreParentClass) {
  85600. _super.prototype._updateCache.call(this);
  85601. }
  85602. this.updateCacheCalled = false;
  85603. };
  85604. /**
  85605. * Updates the current device position and rotation in the babylon world
  85606. */
  85607. WebVRFreeCamera.prototype.update = function () {
  85608. // Get current device position in babylon world
  85609. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  85610. // Get current device rotation in babylon world
  85611. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  85612. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  85613. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  85614. _super.prototype.update.call(this);
  85615. };
  85616. /**
  85617. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  85618. * @returns an identity matrix
  85619. */
  85620. WebVRFreeCamera.prototype._getViewMatrix = function () {
  85621. return BABYLON.Matrix.Identity();
  85622. };
  85623. /**
  85624. * This function is called by the two RIG cameras.
  85625. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  85626. */
  85627. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  85628. var _this = this;
  85629. // Update the parent camera prior to using a child camera to avoid desynchronization
  85630. var parentCamera = this._cameraRigParams["parentCamera"];
  85631. parentCamera._updateCache();
  85632. //WebVR 1.1
  85633. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  85634. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  85635. if (!this.getScene().useRightHandedSystem) {
  85636. [2, 6, 8, 9, 14].forEach(function (num) {
  85637. _this._webvrViewMatrix.m[num] *= -1;
  85638. });
  85639. }
  85640. // update the camera rotation matrix
  85641. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  85642. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  85643. // Computing target and final matrix
  85644. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  85645. // should the view matrix be updated with scale and position offset?
  85646. if (parentCamera.deviceScaleFactor !== 1) {
  85647. this._webvrViewMatrix.invert();
  85648. // scale the position, if set
  85649. if (parentCamera.deviceScaleFactor) {
  85650. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  85651. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  85652. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  85653. }
  85654. this._webvrViewMatrix.invert();
  85655. }
  85656. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  85657. return this._webvrViewMatrix;
  85658. };
  85659. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  85660. var _this = this;
  85661. var parentCamera = this.parent;
  85662. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  85663. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  85664. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  85665. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  85666. //babylon compatible matrix
  85667. if (!this.getScene().useRightHandedSystem) {
  85668. [8, 9, 10, 11].forEach(function (num) {
  85669. _this._projectionMatrix.m[num] *= -1;
  85670. });
  85671. }
  85672. return this._projectionMatrix;
  85673. };
  85674. /**
  85675. * Initializes the controllers and their meshes
  85676. */
  85677. WebVRFreeCamera.prototype.initControllers = function () {
  85678. var _this = this;
  85679. this.controllers = [];
  85680. var manager = this.getScene().gamepadManager;
  85681. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  85682. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85683. var webVrController = gamepad;
  85684. if (webVrController.defaultModel) {
  85685. webVrController.defaultModel.setEnabled(false);
  85686. }
  85687. if (webVrController.hand === "right") {
  85688. _this._rightController = null;
  85689. }
  85690. if (webVrController.hand === "left") {
  85691. _this._leftController = null;
  85692. }
  85693. var controllerIndex = _this.controllers.indexOf(webVrController);
  85694. if (controllerIndex !== -1) {
  85695. _this.controllers.splice(controllerIndex, 1);
  85696. }
  85697. }
  85698. });
  85699. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  85700. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85701. var webVrController_1 = gamepad;
  85702. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  85703. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  85704. if (_this.webVROptions.controllerMeshes) {
  85705. if (webVrController_1.defaultModel) {
  85706. webVrController_1.defaultModel.setEnabled(true);
  85707. }
  85708. else {
  85709. // Load the meshes
  85710. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  85711. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  85712. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  85713. if (_this.webVROptions.defaultLightingOnControllers) {
  85714. if (!_this._lightOnControllers) {
  85715. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  85716. }
  85717. var activateLightOnSubMeshes_1 = function (mesh, light) {
  85718. var children = mesh.getChildren();
  85719. if (children.length !== 0) {
  85720. children.forEach(function (mesh) {
  85721. light.includedOnlyMeshes.push(mesh);
  85722. activateLightOnSubMeshes_1(mesh, light);
  85723. });
  85724. }
  85725. };
  85726. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  85727. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  85728. }
  85729. });
  85730. }
  85731. }
  85732. webVrController_1.attachToPoseControlledCamera(_this);
  85733. // since this is async - sanity check. Is the controller already stored?
  85734. if (_this.controllers.indexOf(webVrController_1) === -1) {
  85735. //add to the controllers array
  85736. _this.controllers.push(webVrController_1);
  85737. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  85738. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  85739. // So we're overriding setting left & right manually to be sure
  85740. var firstViveWandDetected = false;
  85741. for (var i = 0; i < _this.controllers.length; i++) {
  85742. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85743. if (!firstViveWandDetected) {
  85744. firstViveWandDetected = true;
  85745. _this.controllers[i].hand = "left";
  85746. }
  85747. else {
  85748. _this.controllers[i].hand = "right";
  85749. }
  85750. }
  85751. }
  85752. //did we find enough controllers? Great! let the developer know.
  85753. if (_this.controllers.length >= 2) {
  85754. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  85755. }
  85756. }
  85757. }
  85758. });
  85759. };
  85760. return WebVRFreeCamera;
  85761. }(BABYLON.FreeCamera));
  85762. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  85763. })(BABYLON || (BABYLON = {}));
  85764. //# sourceMappingURL=babylon.webVRCamera.js.map
  85765. "use strict";
  85766. var BABYLON;
  85767. (function (BABYLON) {
  85768. // We're mainly based on the logic defined into the FreeCamera code
  85769. /**
  85770. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  85771. * being tilted forward or back and left or right.
  85772. */
  85773. var DeviceOrientationCamera = /** @class */ (function (_super) {
  85774. __extends(DeviceOrientationCamera, _super);
  85775. /**
  85776. * Creates a new device orientation camera
  85777. * @param name The name of the camera
  85778. * @param position The start position camera
  85779. * @param scene The scene the camera belongs to
  85780. */
  85781. function DeviceOrientationCamera(name, position, scene) {
  85782. var _this = _super.call(this, name, position, scene) || this;
  85783. _this._quaternionCache = new BABYLON.Quaternion();
  85784. _this.inputs.addDeviceOrientation();
  85785. return _this;
  85786. }
  85787. /**
  85788. * Gets the current instance class name ("DeviceOrientationCamera").
  85789. * This helps avoiding instanceof at run time.
  85790. * @returns the class name
  85791. */
  85792. DeviceOrientationCamera.prototype.getClassName = function () {
  85793. return "DeviceOrientationCamera";
  85794. };
  85795. /**
  85796. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  85797. */
  85798. DeviceOrientationCamera.prototype._checkInputs = function () {
  85799. _super.prototype._checkInputs.call(this);
  85800. this._quaternionCache.copyFrom(this.rotationQuaternion);
  85801. if (this._initialQuaternion) {
  85802. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85803. }
  85804. };
  85805. /**
  85806. * Reset the camera to its default orientation on the specified axis only.
  85807. * @param axis The axis to reset
  85808. */
  85809. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  85810. var _this = this;
  85811. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  85812. //can only work if this camera has a rotation quaternion already.
  85813. if (!this.rotationQuaternion)
  85814. return;
  85815. if (!this._initialQuaternion) {
  85816. this._initialQuaternion = new BABYLON.Quaternion();
  85817. }
  85818. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  85819. ['x', 'y', 'z'].forEach(function (axisName) {
  85820. if (!axis[axisName]) {
  85821. _this._initialQuaternion[axisName] = 0;
  85822. }
  85823. else {
  85824. _this._initialQuaternion[axisName] *= -1;
  85825. }
  85826. });
  85827. this._initialQuaternion.normalize();
  85828. //force rotation update
  85829. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85830. };
  85831. return DeviceOrientationCamera;
  85832. }(BABYLON.FreeCamera));
  85833. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  85834. })(BABYLON || (BABYLON = {}));
  85835. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  85836. "use strict";
  85837. var BABYLON;
  85838. (function (BABYLON) {
  85839. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  85840. __extends(VRDeviceOrientationFreeCamera, _super);
  85841. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85842. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85843. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85844. var _this = _super.call(this, name, position, scene) || this;
  85845. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85846. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85847. return _this;
  85848. }
  85849. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  85850. return "VRDeviceOrientationFreeCamera";
  85851. };
  85852. return VRDeviceOrientationFreeCamera;
  85853. }(BABYLON.DeviceOrientationCamera));
  85854. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  85855. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  85856. __extends(VRDeviceOrientationGamepadCamera, _super);
  85857. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85858. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85859. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85860. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  85861. _this.inputs.addGamepad();
  85862. return _this;
  85863. }
  85864. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  85865. return "VRDeviceOrientationGamepadCamera";
  85866. };
  85867. return VRDeviceOrientationGamepadCamera;
  85868. }(VRDeviceOrientationFreeCamera));
  85869. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  85870. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  85871. __extends(VRDeviceOrientationArcRotateCamera, _super);
  85872. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  85873. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85874. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85875. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85876. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85877. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85878. _this.inputs.addVRDeviceOrientation();
  85879. return _this;
  85880. }
  85881. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  85882. return "VRDeviceOrientationArcRotateCamera";
  85883. };
  85884. return VRDeviceOrientationArcRotateCamera;
  85885. }(BABYLON.ArcRotateCamera));
  85886. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  85887. })(BABYLON || (BABYLON = {}));
  85888. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  85889. "use strict";
  85890. var BABYLON;
  85891. (function (BABYLON) {
  85892. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  85893. __extends(AnaglyphFreeCamera, _super);
  85894. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  85895. var _this = _super.call(this, name, position, scene) || this;
  85896. _this.interaxialDistance = interaxialDistance;
  85897. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85898. return _this;
  85899. }
  85900. AnaglyphFreeCamera.prototype.getClassName = function () {
  85901. return "AnaglyphFreeCamera";
  85902. };
  85903. return AnaglyphFreeCamera;
  85904. }(BABYLON.FreeCamera));
  85905. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  85906. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  85907. __extends(AnaglyphArcRotateCamera, _super);
  85908. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  85909. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85910. _this.interaxialDistance = interaxialDistance;
  85911. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85912. return _this;
  85913. }
  85914. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  85915. return "AnaglyphArcRotateCamera";
  85916. };
  85917. return AnaglyphArcRotateCamera;
  85918. }(BABYLON.ArcRotateCamera));
  85919. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  85920. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  85921. __extends(AnaglyphGamepadCamera, _super);
  85922. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  85923. var _this = _super.call(this, name, position, scene) || this;
  85924. _this.interaxialDistance = interaxialDistance;
  85925. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85926. return _this;
  85927. }
  85928. AnaglyphGamepadCamera.prototype.getClassName = function () {
  85929. return "AnaglyphGamepadCamera";
  85930. };
  85931. return AnaglyphGamepadCamera;
  85932. }(BABYLON.GamepadCamera));
  85933. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  85934. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  85935. __extends(AnaglyphUniversalCamera, _super);
  85936. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  85937. var _this = _super.call(this, name, position, scene) || this;
  85938. _this.interaxialDistance = interaxialDistance;
  85939. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85940. return _this;
  85941. }
  85942. AnaglyphUniversalCamera.prototype.getClassName = function () {
  85943. return "AnaglyphUniversalCamera";
  85944. };
  85945. return AnaglyphUniversalCamera;
  85946. }(BABYLON.UniversalCamera));
  85947. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  85948. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  85949. __extends(StereoscopicFreeCamera, _super);
  85950. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85951. var _this = _super.call(this, name, position, scene) || this;
  85952. _this.interaxialDistance = interaxialDistance;
  85953. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85954. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85955. return _this;
  85956. }
  85957. StereoscopicFreeCamera.prototype.getClassName = function () {
  85958. return "StereoscopicFreeCamera";
  85959. };
  85960. return StereoscopicFreeCamera;
  85961. }(BABYLON.FreeCamera));
  85962. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  85963. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  85964. __extends(StereoscopicArcRotateCamera, _super);
  85965. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  85966. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85967. _this.interaxialDistance = interaxialDistance;
  85968. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85969. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85970. return _this;
  85971. }
  85972. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  85973. return "StereoscopicArcRotateCamera";
  85974. };
  85975. return StereoscopicArcRotateCamera;
  85976. }(BABYLON.ArcRotateCamera));
  85977. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  85978. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  85979. __extends(StereoscopicGamepadCamera, _super);
  85980. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85981. var _this = _super.call(this, name, position, scene) || this;
  85982. _this.interaxialDistance = interaxialDistance;
  85983. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85984. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85985. return _this;
  85986. }
  85987. StereoscopicGamepadCamera.prototype.getClassName = function () {
  85988. return "StereoscopicGamepadCamera";
  85989. };
  85990. return StereoscopicGamepadCamera;
  85991. }(BABYLON.GamepadCamera));
  85992. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  85993. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  85994. __extends(StereoscopicUniversalCamera, _super);
  85995. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85996. var _this = _super.call(this, name, position, scene) || this;
  85997. _this.interaxialDistance = interaxialDistance;
  85998. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85999. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86000. return _this;
  86001. }
  86002. StereoscopicUniversalCamera.prototype.getClassName = function () {
  86003. return "StereoscopicUniversalCamera";
  86004. };
  86005. return StereoscopicUniversalCamera;
  86006. }(BABYLON.UniversalCamera));
  86007. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  86008. })(BABYLON || (BABYLON = {}));
  86009. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  86010. "use strict";
  86011. var BABYLON;
  86012. (function (BABYLON) {
  86013. var VRExperienceHelperGazer = /** @class */ (function () {
  86014. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  86015. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  86016. this.scene = scene;
  86017. this._pointerDownOnMeshAsked = false;
  86018. this._isActionableMesh = false;
  86019. this._teleportationRequestInitiated = false;
  86020. this._teleportationBackRequestInitiated = false;
  86021. this._dpadPressed = true;
  86022. this._activePointer = false;
  86023. this._id = VRExperienceHelperGazer._idCounter++;
  86024. // Gaze tracker
  86025. if (!gazeTrackerToClone) {
  86026. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  86027. this._gazeTracker.bakeCurrentTransformIntoVertices();
  86028. this._gazeTracker.isPickable = false;
  86029. this._gazeTracker.isVisible = false;
  86030. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  86031. targetMat.specularColor = BABYLON.Color3.Black();
  86032. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86033. targetMat.backFaceCulling = false;
  86034. this._gazeTracker.material = targetMat;
  86035. }
  86036. else {
  86037. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  86038. }
  86039. }
  86040. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  86041. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  86042. };
  86043. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  86044. this._pointerDownOnMeshAsked = true;
  86045. if (this._currentMeshSelected && this._currentHit) {
  86046. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  86047. }
  86048. };
  86049. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  86050. if (this._currentMeshSelected && this._currentHit) {
  86051. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  86052. }
  86053. this._pointerDownOnMeshAsked = false;
  86054. };
  86055. VRExperienceHelperGazer.prototype._activatePointer = function () {
  86056. this._activePointer = true;
  86057. };
  86058. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  86059. this._activePointer = false;
  86060. };
  86061. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  86062. };
  86063. VRExperienceHelperGazer.prototype.dispose = function () {
  86064. this._interactionsEnabled = false;
  86065. this._teleportationEnabled = false;
  86066. };
  86067. VRExperienceHelperGazer._idCounter = 0;
  86068. return VRExperienceHelperGazer;
  86069. }());
  86070. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  86071. __extends(VRExperienceHelperControllerGazer, _super);
  86072. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  86073. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  86074. _this.webVRController = webVRController;
  86075. // Laser pointer
  86076. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  86077. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  86078. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86079. laserPointerMaterial.alpha = 0.6;
  86080. _this._laserPointer.material = laserPointerMaterial;
  86081. _this._laserPointer.rotation.x = Math.PI / 2;
  86082. _this._laserPointer.position.z = -0.5;
  86083. _this._laserPointer.isVisible = false;
  86084. if (!webVRController.mesh) {
  86085. // Create an empty mesh that is used prior to loading the high quality model
  86086. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  86087. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  86088. preloadPointerPose.rotation.x = -0.7;
  86089. preloadMesh.addChild(preloadPointerPose);
  86090. webVRController.attachToMesh(preloadMesh);
  86091. }
  86092. _this._setLaserPointerParent(webVRController.mesh);
  86093. return _this;
  86094. }
  86095. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  86096. return this.webVRController.getForwardRay(length);
  86097. };
  86098. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  86099. _super.prototype._activatePointer.call(this);
  86100. this._laserPointer.isVisible = true;
  86101. };
  86102. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  86103. _super.prototype._deactivatePointer.call(this);
  86104. this._laserPointer.isVisible = false;
  86105. };
  86106. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  86107. this._laserPointer.material.emissiveColor = color;
  86108. };
  86109. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  86110. var makeNotPick = function (root) {
  86111. root.name += " laserPointer";
  86112. root.getChildMeshes().forEach(function (c) {
  86113. makeNotPick(c);
  86114. });
  86115. };
  86116. makeNotPick(mesh);
  86117. var childMeshes = mesh.getChildMeshes();
  86118. this.webVRController._pointingPoseNode = null;
  86119. for (var i = 0; i < childMeshes.length; i++) {
  86120. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  86121. mesh = childMeshes[i];
  86122. this.webVRController._pointingPoseNode = mesh;
  86123. break;
  86124. }
  86125. }
  86126. this._laserPointer.parent = mesh;
  86127. };
  86128. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  86129. this._laserPointer.scaling.y = distance;
  86130. this._laserPointer.position.z = -distance / 2;
  86131. };
  86132. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  86133. _super.prototype.dispose.call(this);
  86134. this._laserPointer.dispose();
  86135. };
  86136. return VRExperienceHelperControllerGazer;
  86137. }(VRExperienceHelperGazer));
  86138. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  86139. __extends(VRExperienceHelperCameraGazer, _super);
  86140. function VRExperienceHelperCameraGazer(getCamera, scene) {
  86141. var _this = _super.call(this, scene) || this;
  86142. _this.getCamera = getCamera;
  86143. return _this;
  86144. }
  86145. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  86146. var camera = this.getCamera();
  86147. if (camera) {
  86148. return camera.getForwardRay(length);
  86149. }
  86150. else {
  86151. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  86152. }
  86153. };
  86154. return VRExperienceHelperCameraGazer;
  86155. }(VRExperienceHelperGazer));
  86156. /**
  86157. * Helps to quickly add VR support to an existing scene.
  86158. * See http://doc.babylonjs.com/how_to/webvr_helper
  86159. */
  86160. var VRExperienceHelper = /** @class */ (function () {
  86161. /**
  86162. * Instantiates a VRExperienceHelper.
  86163. * Helps to quickly add VR support to an existing scene.
  86164. * @param scene The scene the VRExperienceHelper belongs to.
  86165. * @param webVROptions Options to modify the vr experience helper's behavior.
  86166. */
  86167. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  86168. if (webVROptions === void 0) { webVROptions = {}; }
  86169. var _this = this;
  86170. this.webVROptions = webVROptions;
  86171. // Can the system support WebVR, even if a headset isn't plugged in?
  86172. this._webVRsupported = false;
  86173. // If WebVR is supported, is a headset plugged in and are we ready to present?
  86174. this._webVRready = false;
  86175. // Are we waiting for the requestPresent callback to complete?
  86176. this._webVRrequesting = false;
  86177. // Are we presenting to the headset right now?
  86178. this._webVRpresenting = false;
  86179. // Are we presenting in the fullscreen fallback?
  86180. this._fullscreenVRpresenting = false;
  86181. /**
  86182. * Observable raised when entering VR.
  86183. */
  86184. this.onEnteringVRObservable = new BABYLON.Observable();
  86185. /**
  86186. * Observable raised when exiting VR.
  86187. */
  86188. this.onExitingVRObservable = new BABYLON.Observable();
  86189. /**
  86190. * Observable raised when controller mesh is loaded.
  86191. */
  86192. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86193. this._useCustomVRButton = false;
  86194. this._teleportationRequested = false;
  86195. this._teleportActive = false;
  86196. this._floorMeshesCollection = [];
  86197. this._rotationAllowed = true;
  86198. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  86199. this._rotationRightAsked = false;
  86200. this._rotationLeftAsked = false;
  86201. this._isDefaultTeleportationTarget = true;
  86202. this._teleportationFillColor = "#444444";
  86203. this._teleportationBorderColor = "#FFFFFF";
  86204. this._rotationAngle = 0;
  86205. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86206. this._padSensibilityUp = 0.65;
  86207. this._padSensibilityDown = 0.35;
  86208. this.leftController = null;
  86209. this.rightController = null;
  86210. /**
  86211. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86212. */
  86213. this.onNewMeshSelected = new BABYLON.Observable();
  86214. /**
  86215. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86216. */
  86217. this.onNewMeshPicked = new BABYLON.Observable();
  86218. /**
  86219. * Observable raised before camera teleportation
  86220. */
  86221. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86222. /**
  86223. * Observable raised after camera teleportation
  86224. */
  86225. this.onAfterCameraTeleport = new BABYLON.Observable();
  86226. /**
  86227. * Observable raised when current selected mesh gets unselected
  86228. */
  86229. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86230. /**
  86231. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86232. */
  86233. this.teleportationEnabled = true;
  86234. this._teleportationInitialized = false;
  86235. this._interactionsEnabled = false;
  86236. this._interactionsRequested = false;
  86237. this._displayGaze = true;
  86238. this._displayLaserPointer = true;
  86239. this._onResize = function () {
  86240. _this.moveButtonToBottomRight();
  86241. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86242. _this.exitVR();
  86243. }
  86244. };
  86245. this._onFullscreenChange = function () {
  86246. if (document.fullscreen !== undefined) {
  86247. _this._fullscreenVRpresenting = document.fullscreen;
  86248. }
  86249. else if (document.mozFullScreen !== undefined) {
  86250. _this._fullscreenVRpresenting = document.mozFullScreen;
  86251. }
  86252. else if (document.webkitIsFullScreen !== undefined) {
  86253. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86254. }
  86255. else if (document.msIsFullScreen !== undefined) {
  86256. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86257. }
  86258. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86259. _this.exitVR();
  86260. if (!_this._useCustomVRButton) {
  86261. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86262. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86263. }
  86264. }
  86265. };
  86266. this.beforeRender = function () {
  86267. if (_this.leftController && _this.leftController._activePointer) {
  86268. _this._castRayAndSelectObject(_this.leftController);
  86269. }
  86270. if (_this.rightController && _this.rightController._activePointer) {
  86271. _this._castRayAndSelectObject(_this.rightController);
  86272. }
  86273. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86274. _this._castRayAndSelectObject(_this._cameraGazer);
  86275. }
  86276. else {
  86277. _this._cameraGazer._gazeTracker.isVisible = false;
  86278. }
  86279. };
  86280. this._onNewGamepadConnected = function (gamepad) {
  86281. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86282. if (gamepad.leftStick) {
  86283. gamepad.onleftstickchanged(function (stickValues) {
  86284. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86285. // Listening to classic/xbox gamepad only if no VR controller is active
  86286. if ((!_this.leftController && !_this.rightController) ||
  86287. ((_this.leftController && !_this.leftController._activePointer) &&
  86288. (_this.rightController && !_this.rightController._activePointer))) {
  86289. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  86290. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  86291. }
  86292. }
  86293. });
  86294. }
  86295. if (gamepad.rightStick) {
  86296. gamepad.onrightstickchanged(function (stickValues) {
  86297. if (_this._teleportationInitialized) {
  86298. _this._checkRotate(stickValues, _this._cameraGazer);
  86299. }
  86300. });
  86301. }
  86302. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  86303. gamepad.onbuttondown(function (buttonPressed) {
  86304. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86305. _this._cameraGazer._selectionPointerDown();
  86306. }
  86307. });
  86308. gamepad.onbuttonup(function (buttonPressed) {
  86309. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86310. _this._cameraGazer._selectionPointerUp();
  86311. }
  86312. });
  86313. }
  86314. }
  86315. else {
  86316. var webVRController = gamepad;
  86317. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  86318. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  86319. _this.rightController = controller;
  86320. }
  86321. else {
  86322. _this.leftController = controller;
  86323. }
  86324. _this._tryEnableInteractionOnController(controller);
  86325. }
  86326. };
  86327. // 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
  86328. this._tryEnableInteractionOnController = function (controller) {
  86329. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  86330. _this._enableInteractionOnController(controller);
  86331. }
  86332. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  86333. _this._enableTeleportationOnController(controller);
  86334. }
  86335. };
  86336. this._onNewGamepadDisconnected = function (gamepad) {
  86337. if (gamepad instanceof BABYLON.WebVRController) {
  86338. if (gamepad.hand === "left" && _this.leftController != null) {
  86339. _this.leftController.dispose();
  86340. _this.leftController = null;
  86341. }
  86342. if (gamepad.hand === "right" && _this.rightController != null) {
  86343. _this.rightController.dispose();
  86344. _this.rightController = null;
  86345. }
  86346. }
  86347. };
  86348. this._workingVector = BABYLON.Vector3.Zero();
  86349. this._workingQuaternion = BABYLON.Quaternion.Identity();
  86350. this._workingMatrix = BABYLON.Matrix.Identity();
  86351. this._scene = scene;
  86352. this._canvas = scene.getEngine().getRenderingCanvas();
  86353. // Parse options
  86354. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  86355. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  86356. }
  86357. if (webVROptions.createDeviceOrientationCamera === undefined) {
  86358. webVROptions.createDeviceOrientationCamera = true;
  86359. }
  86360. if (webVROptions.defaultHeight === undefined) {
  86361. webVROptions.defaultHeight = 1.7;
  86362. }
  86363. if (webVROptions.useCustomVRButton) {
  86364. this._useCustomVRButton = true;
  86365. if (webVROptions.customVRButton) {
  86366. this._btnVR = webVROptions.customVRButton;
  86367. }
  86368. }
  86369. if (webVROptions.rayLength) {
  86370. this._rayLength = webVROptions.rayLength;
  86371. }
  86372. this._defaultHeight = webVROptions.defaultHeight;
  86373. if (webVROptions.positionScale) {
  86374. this._rayLength *= webVROptions.positionScale;
  86375. this._defaultHeight *= webVROptions.positionScale;
  86376. }
  86377. // Set position
  86378. if (this._scene.activeCamera) {
  86379. this._position = this._scene.activeCamera.position.clone();
  86380. }
  86381. else {
  86382. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  86383. }
  86384. // Set non-vr camera
  86385. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  86386. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  86387. // Copy data from existing camera
  86388. if (this._scene.activeCamera) {
  86389. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  86390. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  86391. // Set rotation from previous camera
  86392. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  86393. var targetCamera = this._scene.activeCamera;
  86394. if (targetCamera.rotationQuaternion) {
  86395. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  86396. }
  86397. else {
  86398. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  86399. }
  86400. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  86401. }
  86402. }
  86403. this._scene.activeCamera = this._deviceOrientationCamera;
  86404. if (this._canvas) {
  86405. this._scene.activeCamera.attachControl(this._canvas);
  86406. }
  86407. }
  86408. else {
  86409. this._existingCamera = this._scene.activeCamera;
  86410. }
  86411. // Create VR cameras
  86412. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86413. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  86414. }
  86415. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  86416. this._webVRCamera.useStandingMatrix();
  86417. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  86418. // Create default button
  86419. if (!this._useCustomVRButton) {
  86420. this._btnVR = document.createElement("BUTTON");
  86421. this._btnVR.className = "babylonVRicon";
  86422. this._btnVR.id = "babylonVRiconbtn";
  86423. this._btnVR.title = "Click to switch to VR";
  86424. 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) }";
  86425. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  86426. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  86427. // css += ".babylonVRicon.vrdisplaysupported { }";
  86428. // css += ".babylonVRicon.vrdisplayready { }";
  86429. // css += ".babylonVRicon.vrdisplayrequesting { }";
  86430. var style = document.createElement('style');
  86431. style.appendChild(document.createTextNode(css));
  86432. document.getElementsByTagName('head')[0].appendChild(style);
  86433. this.moveButtonToBottomRight();
  86434. }
  86435. // VR button click event
  86436. if (this._btnVR) {
  86437. this._btnVR.addEventListener("click", function () {
  86438. if (!_this.isInVRMode) {
  86439. _this.enterVR();
  86440. }
  86441. else {
  86442. _this.exitVR();
  86443. }
  86444. });
  86445. }
  86446. // Window events
  86447. window.addEventListener("resize", this._onResize);
  86448. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  86449. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  86450. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  86451. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  86452. // Display vr button when headset is connected
  86453. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86454. this.displayVRButton();
  86455. }
  86456. else {
  86457. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  86458. if (e.vrDisplay) {
  86459. _this.displayVRButton();
  86460. }
  86461. });
  86462. }
  86463. // Exiting VR mode using 'ESC' key on desktop
  86464. this._onKeyDown = function (event) {
  86465. if (event.keyCode === 27 && _this.isInVRMode) {
  86466. _this.exitVR();
  86467. }
  86468. };
  86469. document.addEventListener("keydown", this._onKeyDown);
  86470. // Exiting VR mode double tapping the touch screen
  86471. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  86472. if (_this.isInVRMode) {
  86473. _this.exitVR();
  86474. if (_this._fullscreenVRpresenting) {
  86475. _this._scene.getEngine().switchFullscreen(true);
  86476. }
  86477. }
  86478. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  86479. // Listen for WebVR display changes
  86480. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  86481. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  86482. this._onVRRequestPresentStart = function () {
  86483. _this._webVRrequesting = true;
  86484. _this.updateButtonVisibility();
  86485. };
  86486. this._onVRRequestPresentComplete = function (success) {
  86487. _this._webVRrequesting = false;
  86488. _this.updateButtonVisibility();
  86489. };
  86490. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  86491. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  86492. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  86493. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86494. scene.onDisposeObservable.add(function () {
  86495. _this.dispose();
  86496. });
  86497. // Gamepad connection events
  86498. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  86499. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  86500. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  86501. this.updateButtonVisibility();
  86502. //create easing functions
  86503. this._circleEase = new BABYLON.CircleEase();
  86504. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86505. }
  86506. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  86507. /** Return this.onEnteringVRObservable
  86508. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  86509. */
  86510. get: function () {
  86511. return this.onEnteringVRObservable;
  86512. },
  86513. enumerable: true,
  86514. configurable: true
  86515. });
  86516. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  86517. /** Return this.onExitingVRObservable
  86518. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  86519. */
  86520. get: function () {
  86521. return this.onExitingVRObservable;
  86522. },
  86523. enumerable: true,
  86524. configurable: true
  86525. });
  86526. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  86527. /** Return this.onControllerMeshLoadedObservable
  86528. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  86529. */
  86530. get: function () {
  86531. return this.onControllerMeshLoadedObservable;
  86532. },
  86533. enumerable: true,
  86534. configurable: true
  86535. });
  86536. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  86537. /**
  86538. * The mesh used to display where the user is going to teleport.
  86539. */
  86540. get: function () {
  86541. return this._teleportationTarget;
  86542. },
  86543. /**
  86544. * Sets the mesh to be used to display where the user is going to teleport.
  86545. */
  86546. set: function (value) {
  86547. if (value) {
  86548. value.name = "teleportationTarget";
  86549. this._isDefaultTeleportationTarget = false;
  86550. this._teleportationTarget = value;
  86551. }
  86552. },
  86553. enumerable: true,
  86554. configurable: true
  86555. });
  86556. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  86557. /**
  86558. * The mesh used to display where the user is selecting,
  86559. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  86560. * See http://doc.babylonjs.com/resources/baking_transformations
  86561. */
  86562. get: function () {
  86563. return this._cameraGazer._gazeTracker;
  86564. },
  86565. set: function (value) {
  86566. if (value) {
  86567. this._cameraGazer._gazeTracker = value;
  86568. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  86569. this._cameraGazer._gazeTracker.isPickable = false;
  86570. this._cameraGazer._gazeTracker.isVisible = false;
  86571. this._cameraGazer._gazeTracker.name = "gazeTracker";
  86572. if (this.leftController) {
  86573. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86574. }
  86575. if (this.rightController) {
  86576. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  86577. }
  86578. }
  86579. },
  86580. enumerable: true,
  86581. configurable: true
  86582. });
  86583. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  86584. /**
  86585. * If the ray of the gaze should be displayed.
  86586. */
  86587. get: function () {
  86588. return this._displayGaze;
  86589. },
  86590. /**
  86591. * Sets if the ray of the gaze should be displayed.
  86592. */
  86593. set: function (value) {
  86594. this._displayGaze = value;
  86595. if (!value) {
  86596. this._cameraGazer._gazeTracker.isVisible = false;
  86597. if (this.leftController) {
  86598. this.leftController._gazeTracker.isVisible = false;
  86599. }
  86600. if (this.rightController) {
  86601. this.rightController._gazeTracker.isVisible = false;
  86602. }
  86603. }
  86604. },
  86605. enumerable: true,
  86606. configurable: true
  86607. });
  86608. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  86609. /**
  86610. * If the ray of the LaserPointer should be displayed.
  86611. */
  86612. get: function () {
  86613. return this._displayLaserPointer;
  86614. },
  86615. /**
  86616. * Sets if the ray of the LaserPointer should be displayed.
  86617. */
  86618. set: function (value) {
  86619. this._displayLaserPointer = value;
  86620. if (!value) {
  86621. if (this.rightController) {
  86622. this.rightController._deactivatePointer();
  86623. this.rightController._gazeTracker.isVisible = false;
  86624. }
  86625. if (this.leftController) {
  86626. this.leftController._deactivatePointer();
  86627. this.leftController._gazeTracker.isVisible = false;
  86628. }
  86629. }
  86630. else {
  86631. if (this.rightController) {
  86632. this.rightController._activatePointer();
  86633. }
  86634. else if (this.leftController) {
  86635. this.leftController._activatePointer();
  86636. }
  86637. }
  86638. },
  86639. enumerable: true,
  86640. configurable: true
  86641. });
  86642. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  86643. /**
  86644. * The deviceOrientationCamera used as the camera when not in VR.
  86645. */
  86646. get: function () {
  86647. return this._deviceOrientationCamera;
  86648. },
  86649. enumerable: true,
  86650. configurable: true
  86651. });
  86652. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  86653. /**
  86654. * Based on the current WebVR support, returns the current VR camera used.
  86655. */
  86656. get: function () {
  86657. if (this._webVRready) {
  86658. return this._webVRCamera;
  86659. }
  86660. else {
  86661. return this._scene.activeCamera;
  86662. }
  86663. },
  86664. enumerable: true,
  86665. configurable: true
  86666. });
  86667. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  86668. /**
  86669. * The webVRCamera which is used when in VR.
  86670. */
  86671. get: function () {
  86672. return this._webVRCamera;
  86673. },
  86674. enumerable: true,
  86675. configurable: true
  86676. });
  86677. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  86678. /**
  86679. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  86680. */
  86681. get: function () {
  86682. return this._vrDeviceOrientationCamera;
  86683. },
  86684. enumerable: true,
  86685. configurable: true
  86686. });
  86687. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  86688. get: function () {
  86689. var result = this._cameraGazer._teleportationRequestInitiated
  86690. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  86691. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  86692. return result;
  86693. },
  86694. enumerable: true,
  86695. configurable: true
  86696. });
  86697. // Raised when one of the controller has loaded successfully its associated default mesh
  86698. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  86699. if (this.leftController && this.leftController.webVRController == webVRController) {
  86700. if (webVRController.mesh) {
  86701. this.leftController._setLaserPointerParent(webVRController.mesh);
  86702. }
  86703. }
  86704. if (this.rightController && this.rightController.webVRController == webVRController) {
  86705. if (webVRController.mesh) {
  86706. this.rightController._setLaserPointerParent(webVRController.mesh);
  86707. }
  86708. }
  86709. try {
  86710. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  86711. }
  86712. catch (err) {
  86713. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  86714. }
  86715. };
  86716. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  86717. /**
  86718. * Gets a value indicating if we are currently in VR mode.
  86719. */
  86720. get: function () {
  86721. return this._webVRpresenting || this._fullscreenVRpresenting;
  86722. },
  86723. enumerable: true,
  86724. configurable: true
  86725. });
  86726. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  86727. var vrDisplay = this._scene.getEngine().getVRDevice();
  86728. if (vrDisplay) {
  86729. var wasPresenting = this._webVRpresenting;
  86730. // A VR display is connected
  86731. this._webVRpresenting = vrDisplay.isPresenting;
  86732. if (wasPresenting && !this._webVRpresenting)
  86733. this.exitVR();
  86734. }
  86735. else {
  86736. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  86737. }
  86738. this.updateButtonVisibility();
  86739. };
  86740. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  86741. this._webVRsupported = eventArgs.vrSupported;
  86742. this._webVRready = !!eventArgs.vrDisplay;
  86743. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  86744. this.updateButtonVisibility();
  86745. };
  86746. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  86747. if (this._canvas && !this._useCustomVRButton) {
  86748. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  86749. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  86750. }
  86751. };
  86752. VRExperienceHelper.prototype.displayVRButton = function () {
  86753. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  86754. document.body.appendChild(this._btnVR);
  86755. this._btnVRDisplayed = true;
  86756. }
  86757. };
  86758. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  86759. if (!this._btnVR || this._useCustomVRButton) {
  86760. return;
  86761. }
  86762. this._btnVR.className = "babylonVRicon";
  86763. if (this.isInVRMode) {
  86764. this._btnVR.className += " vrdisplaypresenting";
  86765. }
  86766. else {
  86767. if (this._webVRready)
  86768. this._btnVR.className += " vrdisplayready";
  86769. if (this._webVRsupported)
  86770. this._btnVR.className += " vrdisplaysupported";
  86771. if (this._webVRrequesting)
  86772. this._btnVR.className += " vrdisplayrequesting";
  86773. }
  86774. };
  86775. /**
  86776. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  86777. * Otherwise, will use the fullscreen API.
  86778. */
  86779. VRExperienceHelper.prototype.enterVR = function () {
  86780. if (this.onEnteringVRObservable) {
  86781. try {
  86782. this.onEnteringVRObservable.notifyObservers(this);
  86783. }
  86784. catch (err) {
  86785. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  86786. }
  86787. }
  86788. if (this._scene.activeCamera) {
  86789. this._position = this._scene.activeCamera.position.clone();
  86790. // make sure that we return to the last active camera
  86791. this._existingCamera = this._scene.activeCamera;
  86792. }
  86793. if (this._webVRrequesting)
  86794. return;
  86795. // If WebVR is supported and a headset is connected
  86796. if (this._webVRready) {
  86797. if (!this._webVRpresenting) {
  86798. this._webVRCamera.position = this._position;
  86799. this._scene.activeCamera = this._webVRCamera;
  86800. }
  86801. }
  86802. else if (this._vrDeviceOrientationCamera) {
  86803. this._vrDeviceOrientationCamera.position = this._position;
  86804. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  86805. this._scene.getEngine().switchFullscreen(true);
  86806. this.updateButtonVisibility();
  86807. }
  86808. if (this._scene.activeCamera && this._canvas) {
  86809. this._scene.activeCamera.attachControl(this._canvas);
  86810. }
  86811. if (this._interactionsEnabled) {
  86812. this._scene.registerBeforeRender(this.beforeRender);
  86813. }
  86814. };
  86815. /**
  86816. * Attempt to exit VR, or fullscreen.
  86817. */
  86818. VRExperienceHelper.prototype.exitVR = function () {
  86819. if (this.onExitingVRObservable) {
  86820. try {
  86821. this.onExitingVRObservable.notifyObservers(this);
  86822. }
  86823. catch (err) {
  86824. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  86825. }
  86826. }
  86827. if (this._webVRpresenting) {
  86828. this._scene.getEngine().disableVR();
  86829. }
  86830. if (this._scene.activeCamera) {
  86831. this._position = this._scene.activeCamera.position.clone();
  86832. }
  86833. if (this._deviceOrientationCamera) {
  86834. this._deviceOrientationCamera.position = this._position;
  86835. this._scene.activeCamera = this._deviceOrientationCamera;
  86836. if (this._canvas) {
  86837. this._scene.activeCamera.attachControl(this._canvas);
  86838. }
  86839. }
  86840. else if (this._existingCamera) {
  86841. this._existingCamera.position = this._position;
  86842. this._scene.activeCamera = this._existingCamera;
  86843. }
  86844. this.updateButtonVisibility();
  86845. if (this._interactionsEnabled) {
  86846. this._scene.unregisterBeforeRender(this.beforeRender);
  86847. }
  86848. };
  86849. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  86850. /**
  86851. * The position of the vr experience helper.
  86852. */
  86853. get: function () {
  86854. return this._position;
  86855. },
  86856. /**
  86857. * Sets the position of the vr experience helper.
  86858. */
  86859. set: function (value) {
  86860. this._position = value;
  86861. if (this._scene.activeCamera) {
  86862. this._scene.activeCamera.position = value;
  86863. }
  86864. },
  86865. enumerable: true,
  86866. configurable: true
  86867. });
  86868. /**
  86869. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  86870. */
  86871. VRExperienceHelper.prototype.enableInteractions = function () {
  86872. var _this = this;
  86873. if (!this._interactionsEnabled) {
  86874. this._interactionsRequested = true;
  86875. if (this.leftController) {
  86876. this._enableInteractionOnController(this.leftController);
  86877. }
  86878. if (this.rightController) {
  86879. this._enableInteractionOnController(this.rightController);
  86880. }
  86881. this.raySelectionPredicate = function (mesh) {
  86882. return mesh.isVisible;
  86883. };
  86884. this.meshSelectionPredicate = function (mesh) {
  86885. return true;
  86886. };
  86887. this._raySelectionPredicate = function (mesh) {
  86888. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  86889. && mesh.name.indexOf("teleportationTarget") === -1
  86890. && mesh.name.indexOf("torusTeleportation") === -1
  86891. && mesh.name.indexOf("laserPointer") === -1)) {
  86892. return _this.raySelectionPredicate(mesh);
  86893. }
  86894. return false;
  86895. };
  86896. this._interactionsEnabled = true;
  86897. }
  86898. };
  86899. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  86900. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  86901. if (this._floorMeshesCollection[i].id === mesh.id) {
  86902. return true;
  86903. }
  86904. }
  86905. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  86906. return true;
  86907. }
  86908. return false;
  86909. };
  86910. /**
  86911. * Adds a floor mesh to be used for teleportation.
  86912. * @param floorMesh the mesh to be used for teleportation.
  86913. */
  86914. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  86915. if (!this._floorMeshesCollection) {
  86916. return;
  86917. }
  86918. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  86919. return;
  86920. }
  86921. this._floorMeshesCollection.push(floorMesh);
  86922. };
  86923. /**
  86924. * Removes a floor mesh from being used for teleportation.
  86925. * @param floorMesh the mesh to be removed.
  86926. */
  86927. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  86928. if (!this._floorMeshesCollection) {
  86929. return;
  86930. }
  86931. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  86932. if (meshIndex !== -1) {
  86933. this._floorMeshesCollection.splice(meshIndex, 1);
  86934. }
  86935. };
  86936. /**
  86937. * Enables interactions and teleportation using the VR controllers and gaze.
  86938. * @param vrTeleportationOptions options to modify teleportation behavior.
  86939. */
  86940. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  86941. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  86942. if (!this._teleportationInitialized) {
  86943. this._teleportationRequested = true;
  86944. this.enableInteractions();
  86945. if (vrTeleportationOptions.floorMeshName) {
  86946. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  86947. }
  86948. if (vrTeleportationOptions.floorMeshes) {
  86949. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  86950. }
  86951. if (this.leftController != null) {
  86952. this._enableTeleportationOnController(this.leftController);
  86953. }
  86954. if (this.rightController != null) {
  86955. this._enableTeleportationOnController(this.rightController);
  86956. }
  86957. // Creates an image processing post process for the vignette not relying
  86958. // on the main scene configuration for image processing to reduce setup and spaces
  86959. // (gamma/linear) conflicts.
  86960. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  86961. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86962. imageProcessingConfiguration.vignetteEnabled = true;
  86963. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  86964. this._webVRCamera.detachPostProcess(this._postProcessMove);
  86965. this._teleportationInitialized = true;
  86966. if (this._isDefaultTeleportationTarget) {
  86967. this._createTeleportationCircles();
  86968. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  86969. }
  86970. }
  86971. };
  86972. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  86973. var _this = this;
  86974. var controllerMesh = controller.webVRController.mesh;
  86975. if (controllerMesh) {
  86976. controller._interactionsEnabled = true;
  86977. controller._activatePointer();
  86978. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  86979. // Enabling / disabling laserPointer
  86980. if (_this._displayLaserPointer && stateObject.value === 1) {
  86981. if (controller._activePointer) {
  86982. controller._deactivatePointer();
  86983. }
  86984. else {
  86985. controller._activatePointer();
  86986. }
  86987. if (_this.displayGaze) {
  86988. controller._gazeTracker.isVisible = controller._activePointer;
  86989. }
  86990. }
  86991. });
  86992. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  86993. if (!controller._pointerDownOnMeshAsked) {
  86994. if (stateObject.value > _this._padSensibilityUp) {
  86995. controller._selectionPointerDown();
  86996. }
  86997. }
  86998. else if (stateObject.value < _this._padSensibilityDown) {
  86999. controller._selectionPointerUp();
  87000. }
  87001. });
  87002. }
  87003. };
  87004. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  87005. // Dont teleport if another gaze already requested teleportation
  87006. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  87007. return;
  87008. }
  87009. if (!gazer._teleportationRequestInitiated) {
  87010. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  87011. gazer._activatePointer();
  87012. gazer._teleportationRequestInitiated = true;
  87013. }
  87014. }
  87015. else {
  87016. // Listening to the proper controller values changes to confirm teleportation
  87017. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  87018. if (this._teleportActive) {
  87019. this._teleportCamera(this._haloCenter);
  87020. }
  87021. gazer._teleportationRequestInitiated = false;
  87022. }
  87023. }
  87024. };
  87025. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  87026. // Only rotate when user is not currently selecting a teleportation location
  87027. if (gazer._teleportationRequestInitiated) {
  87028. return;
  87029. }
  87030. if (!this._rotationLeftAsked) {
  87031. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  87032. this._rotationLeftAsked = true;
  87033. if (this._rotationAllowed) {
  87034. this._rotateCamera(false);
  87035. }
  87036. }
  87037. }
  87038. else {
  87039. if (stateObject.x > -this._padSensibilityDown) {
  87040. this._rotationLeftAsked = false;
  87041. }
  87042. }
  87043. if (!this._rotationRightAsked) {
  87044. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  87045. this._rotationRightAsked = true;
  87046. if (this._rotationAllowed) {
  87047. this._rotateCamera(true);
  87048. }
  87049. }
  87050. }
  87051. else {
  87052. if (stateObject.x < this._padSensibilityDown) {
  87053. this._rotationRightAsked = false;
  87054. }
  87055. }
  87056. };
  87057. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  87058. // Only teleport backwards when user is not currently selecting a teleportation location
  87059. if (gazer._teleportationRequestInitiated) {
  87060. return;
  87061. }
  87062. // Teleport backwards
  87063. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  87064. if (!gazer._teleportationBackRequestInitiated) {
  87065. if (!this.currentVRCamera) {
  87066. return;
  87067. }
  87068. // Get rotation and position of the current camera
  87069. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  87070. var position = this.currentVRCamera.position;
  87071. // If the camera has device position, use that instead
  87072. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  87073. rotation = this.currentVRCamera.deviceRotationQuaternion;
  87074. position = this.currentVRCamera.devicePosition;
  87075. }
  87076. // Get matrix with only the y rotation of the device rotation
  87077. rotation.toEulerAnglesToRef(this._workingVector);
  87078. this._workingVector.z = 0;
  87079. this._workingVector.x = 0;
  87080. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  87081. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  87082. // Rotate backwards ray by device rotation to cast at the ground behind the user
  87083. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  87084. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  87085. var ray = new BABYLON.Ray(position, this._workingVector);
  87086. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  87087. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  87088. this._teleportCamera(hit.pickedPoint);
  87089. }
  87090. gazer._teleportationBackRequestInitiated = true;
  87091. }
  87092. }
  87093. else {
  87094. gazer._teleportationBackRequestInitiated = false;
  87095. }
  87096. };
  87097. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  87098. var _this = this;
  87099. var controllerMesh = controller.webVRController.mesh;
  87100. if (controllerMesh) {
  87101. if (!controller._interactionsEnabled) {
  87102. this._enableInteractionOnController(controller);
  87103. }
  87104. controller._interactionsEnabled = true;
  87105. controller._teleportationEnabled = true;
  87106. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87107. controller._dpadPressed = false;
  87108. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  87109. controller._dpadPressed = stateObject.pressed;
  87110. if (!controller._dpadPressed) {
  87111. _this._rotationLeftAsked = false;
  87112. _this._rotationRightAsked = false;
  87113. controller._teleportationBackRequestInitiated = false;
  87114. }
  87115. });
  87116. }
  87117. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  87118. if (_this.teleportationEnabled) {
  87119. _this._checkTeleportBackwards(stateObject, controller);
  87120. _this._checkTeleportWithRay(stateObject, controller);
  87121. }
  87122. _this._checkRotate(stateObject, controller);
  87123. });
  87124. }
  87125. };
  87126. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  87127. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  87128. this._teleportationTarget.isPickable = false;
  87129. var length = 512;
  87130. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  87131. dynamicTexture.hasAlpha = true;
  87132. var context = dynamicTexture.getContext();
  87133. var centerX = length / 2;
  87134. var centerY = length / 2;
  87135. var radius = 200;
  87136. context.beginPath();
  87137. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  87138. context.fillStyle = this._teleportationFillColor;
  87139. context.fill();
  87140. context.lineWidth = 10;
  87141. context.strokeStyle = this._teleportationBorderColor;
  87142. context.stroke();
  87143. context.closePath();
  87144. dynamicTexture.update();
  87145. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  87146. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  87147. this._teleportationTarget.material = teleportationCircleMaterial;
  87148. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  87149. torus.isPickable = false;
  87150. torus.parent = this._teleportationTarget;
  87151. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87152. var keys = [];
  87153. keys.push({
  87154. frame: 0,
  87155. value: 0
  87156. });
  87157. keys.push({
  87158. frame: 30,
  87159. value: 0.4
  87160. });
  87161. keys.push({
  87162. frame: 60,
  87163. value: 0
  87164. });
  87165. animationInnerCircle.setKeys(keys);
  87166. var easingFunction = new BABYLON.SineEase();
  87167. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87168. animationInnerCircle.setEasingFunction(easingFunction);
  87169. torus.animations = [];
  87170. torus.animations.push(animationInnerCircle);
  87171. this._scene.beginAnimation(torus, 0, 60, true);
  87172. this._hideTeleportationTarget();
  87173. };
  87174. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  87175. this._teleportActive = true;
  87176. if (this._teleportationInitialized) {
  87177. this._teleportationTarget.isVisible = true;
  87178. if (this._isDefaultTeleportationTarget) {
  87179. this._teleportationTarget.getChildren()[0].isVisible = true;
  87180. }
  87181. }
  87182. };
  87183. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  87184. this._teleportActive = false;
  87185. if (this._teleportationInitialized) {
  87186. this._teleportationTarget.isVisible = false;
  87187. if (this._isDefaultTeleportationTarget) {
  87188. this._teleportationTarget.getChildren()[0].isVisible = false;
  87189. }
  87190. }
  87191. };
  87192. VRExperienceHelper.prototype._rotateCamera = function (right) {
  87193. var _this = this;
  87194. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87195. return;
  87196. }
  87197. if (right) {
  87198. this._rotationAngle++;
  87199. }
  87200. else {
  87201. this._rotationAngle--;
  87202. }
  87203. this.currentVRCamera.animations = [];
  87204. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87205. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87206. var animationRotationKeys = [];
  87207. animationRotationKeys.push({
  87208. frame: 0,
  87209. value: this.currentVRCamera.rotationQuaternion
  87210. });
  87211. animationRotationKeys.push({
  87212. frame: 6,
  87213. value: target
  87214. });
  87215. animationRotation.setKeys(animationRotationKeys);
  87216. animationRotation.setEasingFunction(this._circleEase);
  87217. this.currentVRCamera.animations.push(animationRotation);
  87218. this._postProcessMove.animations = [];
  87219. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87220. var vignetteWeightKeys = [];
  87221. vignetteWeightKeys.push({
  87222. frame: 0,
  87223. value: 0
  87224. });
  87225. vignetteWeightKeys.push({
  87226. frame: 3,
  87227. value: 4
  87228. });
  87229. vignetteWeightKeys.push({
  87230. frame: 6,
  87231. value: 0
  87232. });
  87233. animationPP.setKeys(vignetteWeightKeys);
  87234. animationPP.setEasingFunction(this._circleEase);
  87235. this._postProcessMove.animations.push(animationPP);
  87236. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87237. var vignetteStretchKeys = [];
  87238. vignetteStretchKeys.push({
  87239. frame: 0,
  87240. value: 0
  87241. });
  87242. vignetteStretchKeys.push({
  87243. frame: 3,
  87244. value: 10
  87245. });
  87246. vignetteStretchKeys.push({
  87247. frame: 6,
  87248. value: 0
  87249. });
  87250. animationPP2.setKeys(vignetteStretchKeys);
  87251. animationPP2.setEasingFunction(this._circleEase);
  87252. this._postProcessMove.animations.push(animationPP2);
  87253. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87254. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87255. this._postProcessMove.samples = 4;
  87256. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87257. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87258. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87259. });
  87260. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87261. };
  87262. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87263. if (hit.pickedPoint) {
  87264. if (gazer._teleportationRequestInitiated) {
  87265. this._displayTeleportationTarget();
  87266. this._haloCenter.copyFrom(hit.pickedPoint);
  87267. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87268. }
  87269. var pickNormal = hit.getNormal(true, false);
  87270. if (pickNormal) {
  87271. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87272. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87273. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87274. }
  87275. this._teleportationTarget.position.y += 0.1;
  87276. }
  87277. };
  87278. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87279. var _this = this;
  87280. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87281. return;
  87282. }
  87283. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  87284. // offset of the headset from the anchor.
  87285. if (this.webVRCamera.leftCamera) {
  87286. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  87287. this._workingVector.subtractInPlace(this.webVRCamera.position);
  87288. location.subtractToRef(this._workingVector, this._workingVector);
  87289. }
  87290. else {
  87291. this._workingVector.copyFrom(location);
  87292. }
  87293. // Add height to account for user's height offset
  87294. if (this.isInVRMode) {
  87295. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  87296. }
  87297. else {
  87298. this._workingVector.y += this._defaultHeight;
  87299. }
  87300. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  87301. // Create animation from the camera's position to the new location
  87302. this.currentVRCamera.animations = [];
  87303. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87304. var animationCameraTeleportationKeys = [{
  87305. frame: 0,
  87306. value: this.currentVRCamera.position
  87307. },
  87308. {
  87309. frame: 11,
  87310. value: this._workingVector
  87311. }
  87312. ];
  87313. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  87314. animationCameraTeleportation.setEasingFunction(this._circleEase);
  87315. this.currentVRCamera.animations.push(animationCameraTeleportation);
  87316. this._postProcessMove.animations = [];
  87317. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87318. var vignetteWeightKeys = [];
  87319. vignetteWeightKeys.push({
  87320. frame: 0,
  87321. value: 0
  87322. });
  87323. vignetteWeightKeys.push({
  87324. frame: 5,
  87325. value: 8
  87326. });
  87327. vignetteWeightKeys.push({
  87328. frame: 11,
  87329. value: 0
  87330. });
  87331. animationPP.setKeys(vignetteWeightKeys);
  87332. this._postProcessMove.animations.push(animationPP);
  87333. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87334. var vignetteStretchKeys = [];
  87335. vignetteStretchKeys.push({
  87336. frame: 0,
  87337. value: 0
  87338. });
  87339. vignetteStretchKeys.push({
  87340. frame: 5,
  87341. value: 10
  87342. });
  87343. vignetteStretchKeys.push({
  87344. frame: 11,
  87345. value: 0
  87346. });
  87347. animationPP2.setKeys(vignetteStretchKeys);
  87348. this._postProcessMove.animations.push(animationPP2);
  87349. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87350. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87351. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87352. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  87353. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87354. });
  87355. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  87356. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  87357. });
  87358. this._hideTeleportationTarget();
  87359. };
  87360. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  87361. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87362. return;
  87363. }
  87364. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  87365. // Moving the gazeTracker on the mesh face targetted
  87366. if (hit && hit.pickedPoint) {
  87367. if (this._displayGaze) {
  87368. var multiplier = 1;
  87369. gazer._gazeTracker.isVisible = true;
  87370. if (gazer._isActionableMesh) {
  87371. multiplier = 3;
  87372. }
  87373. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  87374. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  87375. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  87376. var pickNormal = hit.getNormal();
  87377. // To avoid z-fighting
  87378. var deltaFighting = 0.002;
  87379. if (pickNormal) {
  87380. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87381. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87382. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  87383. }
  87384. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  87385. if (gazer._gazeTracker.position.x < 0) {
  87386. gazer._gazeTracker.position.x += deltaFighting;
  87387. }
  87388. else {
  87389. gazer._gazeTracker.position.x -= deltaFighting;
  87390. }
  87391. if (gazer._gazeTracker.position.y < 0) {
  87392. gazer._gazeTracker.position.y += deltaFighting;
  87393. }
  87394. else {
  87395. gazer._gazeTracker.position.y -= deltaFighting;
  87396. }
  87397. if (gazer._gazeTracker.position.z < 0) {
  87398. gazer._gazeTracker.position.z += deltaFighting;
  87399. }
  87400. else {
  87401. gazer._gazeTracker.position.z -= deltaFighting;
  87402. }
  87403. }
  87404. // Changing the size of the laser pointer based on the distance from the targetted point
  87405. gazer._updatePointerDistance(hit.distance);
  87406. }
  87407. else {
  87408. gazer._gazeTracker.isVisible = false;
  87409. }
  87410. if (hit && hit.pickedMesh) {
  87411. gazer._currentHit = hit;
  87412. if (gazer._pointerDownOnMeshAsked) {
  87413. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  87414. }
  87415. // The object selected is the floor, we're in a teleportation scenario
  87416. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  87417. // Moving the teleportation area to this targetted point
  87418. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  87419. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  87420. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87421. }
  87422. gazer._currentMeshSelected = null;
  87423. if (gazer._teleportationRequestInitiated) {
  87424. this._moveTeleportationSelectorTo(hit, gazer);
  87425. }
  87426. return;
  87427. }
  87428. // If not, we're in a selection scenario
  87429. //this._teleportationAllowed = false;
  87430. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  87431. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  87432. this.onNewMeshPicked.notifyObservers(hit);
  87433. gazer._currentMeshSelected = hit.pickedMesh;
  87434. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  87435. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  87436. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  87437. gazer._isActionableMesh = true;
  87438. }
  87439. else {
  87440. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87441. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87442. gazer._isActionableMesh = false;
  87443. }
  87444. try {
  87445. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  87446. }
  87447. catch (err) {
  87448. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  87449. }
  87450. }
  87451. else {
  87452. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87453. gazer._currentMeshSelected = null;
  87454. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87455. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87456. }
  87457. }
  87458. }
  87459. else {
  87460. gazer._currentHit = null;
  87461. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87462. gazer._currentMeshSelected = null;
  87463. //this._teleportationAllowed = false;
  87464. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87465. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87466. }
  87467. };
  87468. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  87469. if (mesh) {
  87470. this.onSelectedMeshUnselected.notifyObservers(mesh);
  87471. }
  87472. };
  87473. /**
  87474. * Sets the color of the laser ray from the vr controllers.
  87475. * @param color new color for the ray.
  87476. */
  87477. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  87478. if (this.leftController) {
  87479. this.leftController._setLaserPointerColor(color);
  87480. }
  87481. if (this.rightController) {
  87482. this.rightController._setLaserPointerColor(color);
  87483. }
  87484. };
  87485. /**
  87486. * Sets the color of the ray from the vr headsets gaze.
  87487. * @param color new color for the ray.
  87488. */
  87489. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  87490. if (!this._cameraGazer._gazeTracker.material) {
  87491. return;
  87492. }
  87493. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  87494. if (this.leftController) {
  87495. this.leftController._gazeTracker.material.emissiveColor = color;
  87496. }
  87497. if (this.rightController) {
  87498. this.rightController._gazeTracker.material.emissiveColor = color;
  87499. }
  87500. };
  87501. /**
  87502. * Exits VR and disposes of the vr experience helper
  87503. */
  87504. VRExperienceHelper.prototype.dispose = function () {
  87505. if (this.isInVRMode) {
  87506. this.exitVR();
  87507. }
  87508. if (this._postProcessMove) {
  87509. this._postProcessMove.dispose();
  87510. }
  87511. if (this._webVRCamera) {
  87512. this._webVRCamera.dispose();
  87513. }
  87514. if (this._vrDeviceOrientationCamera) {
  87515. this._vrDeviceOrientationCamera.dispose();
  87516. }
  87517. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  87518. document.body.removeChild(this._btnVR);
  87519. }
  87520. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  87521. this._deviceOrientationCamera.dispose();
  87522. }
  87523. if (this._cameraGazer) {
  87524. this._cameraGazer.dispose();
  87525. }
  87526. if (this.leftController) {
  87527. this.leftController.dispose();
  87528. }
  87529. if (this.rightController) {
  87530. this.rightController.dispose();
  87531. }
  87532. if (this._teleportationTarget) {
  87533. this._teleportationTarget.dispose();
  87534. }
  87535. this._floorMeshesCollection = [];
  87536. document.removeEventListener("keydown", this._onKeyDown);
  87537. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87538. window.removeEventListener("resize", this._onResize);
  87539. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  87540. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  87541. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  87542. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  87543. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  87544. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  87545. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  87546. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87547. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  87548. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  87549. this._scene.unregisterBeforeRender(this.beforeRender);
  87550. };
  87551. /**
  87552. * Gets the name of the VRExperienceHelper class
  87553. * @returns "VRExperienceHelper"
  87554. */
  87555. VRExperienceHelper.prototype.getClassName = function () {
  87556. return "VRExperienceHelper";
  87557. };
  87558. return VRExperienceHelper;
  87559. }());
  87560. BABYLON.VRExperienceHelper = VRExperienceHelper;
  87561. })(BABYLON || (BABYLON = {}));
  87562. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  87563. "use strict";
  87564. // Mainly based on these 2 articles :
  87565. // 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
  87566. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  87567. var BABYLON;
  87568. (function (BABYLON) {
  87569. var JoystickAxis;
  87570. (function (JoystickAxis) {
  87571. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  87572. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  87573. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  87574. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  87575. var VirtualJoystick = /** @class */ (function () {
  87576. function VirtualJoystick(leftJoystick) {
  87577. var _this = this;
  87578. if (leftJoystick) {
  87579. this._leftJoystick = true;
  87580. }
  87581. else {
  87582. this._leftJoystick = false;
  87583. }
  87584. VirtualJoystick._globalJoystickIndex++;
  87585. // By default left & right arrow keys are moving the X
  87586. // and up & down keys are moving the Y
  87587. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87588. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87589. this.reverseLeftRight = false;
  87590. this.reverseUpDown = false;
  87591. // collections of pointers
  87592. this._touches = new BABYLON.StringDictionary();
  87593. this.deltaPosition = BABYLON.Vector3.Zero();
  87594. this._joystickSensibility = 25;
  87595. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87596. this._onResize = function (evt) {
  87597. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87598. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87599. if (VirtualJoystick.vjCanvas) {
  87600. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  87601. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  87602. }
  87603. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  87604. };
  87605. // injecting a canvas element on top of the canvas 3D game
  87606. if (!VirtualJoystick.vjCanvas) {
  87607. window.addEventListener("resize", this._onResize, false);
  87608. VirtualJoystick.vjCanvas = document.createElement("canvas");
  87609. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  87610. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  87611. VirtualJoystick.vjCanvas.width = window.innerWidth;
  87612. VirtualJoystick.vjCanvas.height = window.innerHeight;
  87613. VirtualJoystick.vjCanvas.style.width = "100%";
  87614. VirtualJoystick.vjCanvas.style.height = "100%";
  87615. VirtualJoystick.vjCanvas.style.position = "absolute";
  87616. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  87617. VirtualJoystick.vjCanvas.style.top = "0px";
  87618. VirtualJoystick.vjCanvas.style.left = "0px";
  87619. VirtualJoystick.vjCanvas.style.zIndex = "5";
  87620. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  87621. // Support for jQuery PEP polyfill
  87622. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  87623. var context = VirtualJoystick.vjCanvas.getContext('2d');
  87624. if (!context) {
  87625. throw new Error("Unable to create canvas for virtual joystick");
  87626. }
  87627. VirtualJoystick.vjCanvasContext = context;
  87628. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  87629. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87630. document.body.appendChild(VirtualJoystick.vjCanvas);
  87631. }
  87632. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  87633. this.pressed = false;
  87634. // default joystick color
  87635. this._joystickColor = "cyan";
  87636. this._joystickPointerID = -1;
  87637. // current joystick position
  87638. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  87639. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  87640. // origin joystick position
  87641. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  87642. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  87643. this._onPointerDownHandlerRef = function (evt) {
  87644. _this._onPointerDown(evt);
  87645. };
  87646. this._onPointerMoveHandlerRef = function (evt) {
  87647. _this._onPointerMove(evt);
  87648. };
  87649. this._onPointerUpHandlerRef = function (evt) {
  87650. _this._onPointerUp(evt);
  87651. };
  87652. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  87653. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  87654. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  87655. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  87656. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  87657. evt.preventDefault(); // Disables system menu
  87658. }, false);
  87659. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87660. }
  87661. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  87662. this._joystickSensibility = newJoystickSensibility;
  87663. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  87664. };
  87665. VirtualJoystick.prototype._onPointerDown = function (e) {
  87666. var positionOnScreenCondition;
  87667. e.preventDefault();
  87668. if (this._leftJoystick === true) {
  87669. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  87670. }
  87671. else {
  87672. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  87673. }
  87674. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  87675. // First contact will be dedicated to the virtual joystick
  87676. this._joystickPointerID = e.pointerId;
  87677. this._joystickPointerStartPos.x = e.clientX;
  87678. this._joystickPointerStartPos.y = e.clientY;
  87679. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  87680. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  87681. this._deltaJoystickVector.x = 0;
  87682. this._deltaJoystickVector.y = 0;
  87683. this.pressed = true;
  87684. this._touches.add(e.pointerId.toString(), e);
  87685. }
  87686. else {
  87687. // You can only trigger the action buttons with a joystick declared
  87688. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  87689. this._action();
  87690. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  87691. }
  87692. }
  87693. };
  87694. VirtualJoystick.prototype._onPointerMove = function (e) {
  87695. // If the current pointer is the one associated to the joystick (first touch contact)
  87696. if (this._joystickPointerID == e.pointerId) {
  87697. this._joystickPointerPos.x = e.clientX;
  87698. this._joystickPointerPos.y = e.clientY;
  87699. this._deltaJoystickVector = this._joystickPointerPos.clone();
  87700. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  87701. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  87702. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  87703. switch (this._axisTargetedByLeftAndRight) {
  87704. case JoystickAxis.X:
  87705. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  87706. break;
  87707. case JoystickAxis.Y:
  87708. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  87709. break;
  87710. case JoystickAxis.Z:
  87711. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  87712. break;
  87713. }
  87714. var directionUpDown = this.reverseUpDown ? 1 : -1;
  87715. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  87716. switch (this._axisTargetedByUpAndDown) {
  87717. case JoystickAxis.X:
  87718. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  87719. break;
  87720. case JoystickAxis.Y:
  87721. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  87722. break;
  87723. case JoystickAxis.Z:
  87724. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  87725. break;
  87726. }
  87727. }
  87728. else {
  87729. var data = this._touches.get(e.pointerId.toString());
  87730. if (data) {
  87731. data.x = e.clientX;
  87732. data.y = e.clientY;
  87733. }
  87734. }
  87735. };
  87736. VirtualJoystick.prototype._onPointerUp = function (e) {
  87737. if (this._joystickPointerID == e.pointerId) {
  87738. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  87739. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  87740. this._joystickPointerID = -1;
  87741. this.pressed = false;
  87742. }
  87743. else {
  87744. var touch = this._touches.get(e.pointerId.toString());
  87745. if (touch) {
  87746. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87747. }
  87748. }
  87749. this._deltaJoystickVector.x = 0;
  87750. this._deltaJoystickVector.y = 0;
  87751. this._touches.remove(e.pointerId.toString());
  87752. };
  87753. /**
  87754. * Change the color of the virtual joystick
  87755. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  87756. */
  87757. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  87758. this._joystickColor = newColor;
  87759. };
  87760. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  87761. this._action = action;
  87762. };
  87763. // Define which axis you'd like to control for left & right
  87764. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  87765. switch (axis) {
  87766. case JoystickAxis.X:
  87767. case JoystickAxis.Y:
  87768. case JoystickAxis.Z:
  87769. this._axisTargetedByLeftAndRight = axis;
  87770. break;
  87771. default:
  87772. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87773. break;
  87774. }
  87775. };
  87776. // Define which axis you'd like to control for up & down
  87777. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  87778. switch (axis) {
  87779. case JoystickAxis.X:
  87780. case JoystickAxis.Y:
  87781. case JoystickAxis.Z:
  87782. this._axisTargetedByUpAndDown = axis;
  87783. break;
  87784. default:
  87785. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87786. break;
  87787. }
  87788. };
  87789. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  87790. var _this = this;
  87791. if (this.pressed) {
  87792. this._touches.forEach(function (key, touch) {
  87793. if (touch.pointerId === _this._joystickPointerID) {
  87794. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  87795. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  87796. VirtualJoystick.vjCanvasContext.beginPath();
  87797. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87798. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87799. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  87800. VirtualJoystick.vjCanvasContext.stroke();
  87801. VirtualJoystick.vjCanvasContext.closePath();
  87802. VirtualJoystick.vjCanvasContext.beginPath();
  87803. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87804. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87805. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  87806. VirtualJoystick.vjCanvasContext.stroke();
  87807. VirtualJoystick.vjCanvasContext.closePath();
  87808. VirtualJoystick.vjCanvasContext.beginPath();
  87809. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87810. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  87811. VirtualJoystick.vjCanvasContext.stroke();
  87812. VirtualJoystick.vjCanvasContext.closePath();
  87813. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  87814. }
  87815. else {
  87816. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87817. VirtualJoystick.vjCanvasContext.beginPath();
  87818. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  87819. VirtualJoystick.vjCanvasContext.beginPath();
  87820. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  87821. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87822. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  87823. VirtualJoystick.vjCanvasContext.stroke();
  87824. VirtualJoystick.vjCanvasContext.closePath();
  87825. touch.prevX = touch.x;
  87826. touch.prevY = touch.y;
  87827. }
  87828. ;
  87829. });
  87830. }
  87831. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87832. };
  87833. VirtualJoystick.prototype.releaseCanvas = function () {
  87834. if (VirtualJoystick.vjCanvas) {
  87835. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  87836. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  87837. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  87838. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  87839. window.removeEventListener("resize", this._onResize);
  87840. document.body.removeChild(VirtualJoystick.vjCanvas);
  87841. VirtualJoystick.vjCanvas = null;
  87842. }
  87843. };
  87844. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  87845. VirtualJoystick._globalJoystickIndex = 0;
  87846. return VirtualJoystick;
  87847. }());
  87848. BABYLON.VirtualJoystick = VirtualJoystick;
  87849. })(BABYLON || (BABYLON = {}));
  87850. //# sourceMappingURL=babylon.virtualJoystick.js.map
  87851. "use strict";
  87852. var BABYLON;
  87853. (function (BABYLON) {
  87854. // We're mainly based on the logic defined into the FreeCamera code
  87855. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  87856. __extends(VirtualJoysticksCamera, _super);
  87857. function VirtualJoysticksCamera(name, position, scene) {
  87858. var _this = _super.call(this, name, position, scene) || this;
  87859. _this.inputs.addVirtualJoystick();
  87860. return _this;
  87861. }
  87862. VirtualJoysticksCamera.prototype.getClassName = function () {
  87863. return "VirtualJoysticksCamera";
  87864. };
  87865. return VirtualJoysticksCamera;
  87866. }(BABYLON.FreeCamera));
  87867. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  87868. })(BABYLON || (BABYLON = {}));
  87869. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  87870. "use strict";
  87871. var BABYLON;
  87872. (function (BABYLON) {
  87873. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  87874. function FreeCameraVirtualJoystickInput() {
  87875. }
  87876. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  87877. return this._leftjoystick;
  87878. };
  87879. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  87880. return this._rightjoystick;
  87881. };
  87882. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  87883. if (this._leftjoystick) {
  87884. var camera = this.camera;
  87885. var speed = camera._computeLocalCameraSpeed() * 50;
  87886. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  87887. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  87888. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  87889. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  87890. if (!this._leftjoystick.pressed) {
  87891. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  87892. }
  87893. if (!this._rightjoystick.pressed) {
  87894. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  87895. }
  87896. }
  87897. };
  87898. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  87899. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  87900. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  87901. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  87902. this._leftjoystick.setJoystickSensibility(0.15);
  87903. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  87904. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  87905. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  87906. this._rightjoystick.reverseUpDown = true;
  87907. this._rightjoystick.setJoystickSensibility(0.05);
  87908. this._rightjoystick.setJoystickColor("yellow");
  87909. };
  87910. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  87911. this._leftjoystick.releaseCanvas();
  87912. this._rightjoystick.releaseCanvas();
  87913. };
  87914. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  87915. return "FreeCameraVirtualJoystickInput";
  87916. };
  87917. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  87918. return "virtualJoystick";
  87919. };
  87920. return FreeCameraVirtualJoystickInput;
  87921. }());
  87922. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  87923. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  87924. })(BABYLON || (BABYLON = {}));
  87925. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  87926. "use strict";
  87927. var BABYLON;
  87928. (function (BABYLON) {
  87929. var SimplificationSettings = /** @class */ (function () {
  87930. function SimplificationSettings(quality, distance, optimizeMesh) {
  87931. this.quality = quality;
  87932. this.distance = distance;
  87933. this.optimizeMesh = optimizeMesh;
  87934. }
  87935. return SimplificationSettings;
  87936. }());
  87937. BABYLON.SimplificationSettings = SimplificationSettings;
  87938. var SimplificationQueue = /** @class */ (function () {
  87939. function SimplificationQueue() {
  87940. this.running = false;
  87941. this._simplificationArray = [];
  87942. }
  87943. SimplificationQueue.prototype.addTask = function (task) {
  87944. this._simplificationArray.push(task);
  87945. };
  87946. SimplificationQueue.prototype.executeNext = function () {
  87947. var task = this._simplificationArray.pop();
  87948. if (task) {
  87949. this.running = true;
  87950. this.runSimplification(task);
  87951. }
  87952. else {
  87953. this.running = false;
  87954. }
  87955. };
  87956. SimplificationQueue.prototype.runSimplification = function (task) {
  87957. var _this = this;
  87958. if (task.parallelProcessing) {
  87959. //parallel simplifier
  87960. task.settings.forEach(function (setting) {
  87961. var simplifier = _this.getSimplifier(task);
  87962. simplifier.simplify(setting, function (newMesh) {
  87963. task.mesh.addLODLevel(setting.distance, newMesh);
  87964. newMesh.isVisible = true;
  87965. //check if it is the last
  87966. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  87967. //all done, run the success callback.
  87968. task.successCallback();
  87969. }
  87970. _this.executeNext();
  87971. });
  87972. });
  87973. }
  87974. else {
  87975. //single simplifier.
  87976. var simplifier = this.getSimplifier(task);
  87977. var runDecimation = function (setting, callback) {
  87978. simplifier.simplify(setting, function (newMesh) {
  87979. task.mesh.addLODLevel(setting.distance, newMesh);
  87980. newMesh.isVisible = true;
  87981. //run the next quality level
  87982. callback();
  87983. });
  87984. };
  87985. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  87986. runDecimation(task.settings[loop.index], function () {
  87987. loop.executeNext();
  87988. });
  87989. }, function () {
  87990. //execution ended, run the success callback.
  87991. if (task.successCallback) {
  87992. task.successCallback();
  87993. }
  87994. _this.executeNext();
  87995. });
  87996. }
  87997. };
  87998. SimplificationQueue.prototype.getSimplifier = function (task) {
  87999. switch (task.simplificationType) {
  88000. case SimplificationType.QUADRATIC:
  88001. default:
  88002. return new QuadraticErrorSimplification(task.mesh);
  88003. }
  88004. };
  88005. return SimplificationQueue;
  88006. }());
  88007. BABYLON.SimplificationQueue = SimplificationQueue;
  88008. /**
  88009. * The implemented types of simplification.
  88010. * At the moment only Quadratic Error Decimation is implemented.
  88011. */
  88012. var SimplificationType;
  88013. (function (SimplificationType) {
  88014. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  88015. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88016. var DecimationTriangle = /** @class */ (function () {
  88017. function DecimationTriangle(vertices) {
  88018. this.vertices = vertices;
  88019. this.error = new Array(4);
  88020. this.deleted = false;
  88021. this.isDirty = false;
  88022. this.deletePending = false;
  88023. this.borderFactor = 0;
  88024. }
  88025. return DecimationTriangle;
  88026. }());
  88027. BABYLON.DecimationTriangle = DecimationTriangle;
  88028. var DecimationVertex = /** @class */ (function () {
  88029. function DecimationVertex(position, id) {
  88030. this.position = position;
  88031. this.id = id;
  88032. this.isBorder = true;
  88033. this.q = new QuadraticMatrix();
  88034. this.triangleCount = 0;
  88035. this.triangleStart = 0;
  88036. this.originalOffsets = [];
  88037. }
  88038. DecimationVertex.prototype.updatePosition = function (newPosition) {
  88039. this.position.copyFrom(newPosition);
  88040. };
  88041. return DecimationVertex;
  88042. }());
  88043. BABYLON.DecimationVertex = DecimationVertex;
  88044. var QuadraticMatrix = /** @class */ (function () {
  88045. function QuadraticMatrix(data) {
  88046. this.data = new Array(10);
  88047. for (var i = 0; i < 10; ++i) {
  88048. if (data && data[i]) {
  88049. this.data[i] = data[i];
  88050. }
  88051. else {
  88052. this.data[i] = 0;
  88053. }
  88054. }
  88055. }
  88056. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  88057. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  88058. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  88059. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  88060. return det;
  88061. };
  88062. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  88063. for (var i = 0; i < 10; ++i) {
  88064. this.data[i] += matrix.data[i];
  88065. }
  88066. };
  88067. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  88068. for (var i = 0; i < 10; ++i) {
  88069. this.data[i] += data[i];
  88070. }
  88071. };
  88072. QuadraticMatrix.prototype.add = function (matrix) {
  88073. var m = new QuadraticMatrix();
  88074. for (var i = 0; i < 10; ++i) {
  88075. m.data[i] = this.data[i] + matrix.data[i];
  88076. }
  88077. return m;
  88078. };
  88079. QuadraticMatrix.FromData = function (a, b, c, d) {
  88080. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  88081. };
  88082. //returning an array to avoid garbage collection
  88083. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  88084. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  88085. };
  88086. return QuadraticMatrix;
  88087. }());
  88088. BABYLON.QuadraticMatrix = QuadraticMatrix;
  88089. var Reference = /** @class */ (function () {
  88090. function Reference(vertexId, triangleId) {
  88091. this.vertexId = vertexId;
  88092. this.triangleId = triangleId;
  88093. }
  88094. return Reference;
  88095. }());
  88096. BABYLON.Reference = Reference;
  88097. /**
  88098. * An implementation of the Quadratic Error simplification algorithm.
  88099. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  88100. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  88101. * @author RaananW
  88102. */
  88103. var QuadraticErrorSimplification = /** @class */ (function () {
  88104. function QuadraticErrorSimplification(_mesh) {
  88105. this._mesh = _mesh;
  88106. this.syncIterations = 5000;
  88107. this.aggressiveness = 7;
  88108. this.decimationIterations = 100;
  88109. this.boundingBoxEpsilon = BABYLON.Epsilon;
  88110. }
  88111. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  88112. var _this = this;
  88113. this.initDecimatedMesh();
  88114. //iterating through the submeshes array, one after the other.
  88115. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  88116. _this.initWithMesh(loop.index, function () {
  88117. _this.runDecimation(settings, loop.index, function () {
  88118. loop.executeNext();
  88119. });
  88120. }, settings.optimizeMesh);
  88121. }, function () {
  88122. setTimeout(function () {
  88123. successCallback(_this._reconstructedMesh);
  88124. }, 0);
  88125. });
  88126. };
  88127. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  88128. var _this = this;
  88129. var targetCount = ~~(this.triangles.length * settings.quality);
  88130. var deletedTriangles = 0;
  88131. var triangleCount = this.triangles.length;
  88132. var iterationFunction = function (iteration, callback) {
  88133. setTimeout(function () {
  88134. if (iteration % 5 === 0) {
  88135. _this.updateMesh(iteration === 0);
  88136. }
  88137. for (var i = 0; i < _this.triangles.length; ++i) {
  88138. _this.triangles[i].isDirty = false;
  88139. }
  88140. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  88141. var trianglesIterator = function (i) {
  88142. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  88143. var t = _this.triangles[tIdx];
  88144. if (!t)
  88145. return;
  88146. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  88147. return;
  88148. }
  88149. for (var j = 0; j < 3; ++j) {
  88150. if (t.error[j] < threshold) {
  88151. var deleted0 = [];
  88152. var deleted1 = [];
  88153. var v0 = t.vertices[j];
  88154. var v1 = t.vertices[(j + 1) % 3];
  88155. if (v0.isBorder || v1.isBorder)
  88156. continue;
  88157. var p = BABYLON.Vector3.Zero();
  88158. var n = BABYLON.Vector3.Zero();
  88159. var uv = BABYLON.Vector2.Zero();
  88160. var color = new BABYLON.Color4(0, 0, 0, 1);
  88161. _this.calculateError(v0, v1, p, n, uv, color);
  88162. var delTr = new Array();
  88163. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  88164. continue;
  88165. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  88166. continue;
  88167. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  88168. continue;
  88169. var uniqueArray = new Array();
  88170. delTr.forEach(function (deletedT) {
  88171. if (uniqueArray.indexOf(deletedT) === -1) {
  88172. deletedT.deletePending = true;
  88173. uniqueArray.push(deletedT);
  88174. }
  88175. });
  88176. if (uniqueArray.length % 2 !== 0) {
  88177. continue;
  88178. }
  88179. v0.q = v1.q.add(v0.q);
  88180. v0.updatePosition(p);
  88181. var tStart = _this.references.length;
  88182. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  88183. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  88184. var tCount = _this.references.length - tStart;
  88185. if (tCount <= v0.triangleCount) {
  88186. if (tCount) {
  88187. for (var c = 0; c < tCount; c++) {
  88188. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  88189. }
  88190. }
  88191. }
  88192. else {
  88193. v0.triangleStart = tStart;
  88194. }
  88195. v0.triangleCount = tCount;
  88196. break;
  88197. }
  88198. }
  88199. };
  88200. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  88201. }, 0);
  88202. };
  88203. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88204. if (triangleCount - deletedTriangles <= targetCount)
  88205. loop.breakLoop();
  88206. else {
  88207. iterationFunction(loop.index, function () {
  88208. loop.executeNext();
  88209. });
  88210. }
  88211. }, function () {
  88212. setTimeout(function () {
  88213. //reconstruct this part of the mesh
  88214. _this.reconstructMesh(submeshIndex);
  88215. successCallback();
  88216. }, 0);
  88217. });
  88218. };
  88219. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88220. var _this = this;
  88221. this.vertices = [];
  88222. this.triangles = [];
  88223. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88224. var indices = this._mesh.getIndices();
  88225. var submesh = this._mesh.subMeshes[submeshIndex];
  88226. var findInVertices = function (positionToSearch) {
  88227. if (optimizeMesh) {
  88228. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88229. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88230. return _this.vertices[ii];
  88231. }
  88232. }
  88233. }
  88234. return null;
  88235. };
  88236. var vertexReferences = [];
  88237. var vertexInit = function (i) {
  88238. if (!positionData) {
  88239. return;
  88240. }
  88241. var offset = i + submesh.verticesStart;
  88242. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88243. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88244. vertex.originalOffsets.push(offset);
  88245. if (vertex.id === _this.vertices.length) {
  88246. _this.vertices.push(vertex);
  88247. }
  88248. vertexReferences.push(vertex.id);
  88249. };
  88250. //var totalVertices = mesh.getTotalVertices();
  88251. var totalVertices = submesh.verticesCount;
  88252. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88253. var indicesInit = function (i) {
  88254. if (!indices) {
  88255. return;
  88256. }
  88257. var offset = (submesh.indexStart / 3) + i;
  88258. var pos = (offset * 3);
  88259. var i0 = indices[pos + 0];
  88260. var i1 = indices[pos + 1];
  88261. var i2 = indices[pos + 2];
  88262. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  88263. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  88264. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  88265. var triangle = new DecimationTriangle([v0, v1, v2]);
  88266. triangle.originalOffset = pos;
  88267. _this.triangles.push(triangle);
  88268. };
  88269. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  88270. _this.init(callback);
  88271. });
  88272. });
  88273. };
  88274. QuadraticErrorSimplification.prototype.init = function (callback) {
  88275. var _this = this;
  88276. var triangleInit1 = function (i) {
  88277. var t = _this.triangles[i];
  88278. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  88279. for (var j = 0; j < 3; j++) {
  88280. 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))));
  88281. }
  88282. };
  88283. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  88284. var triangleInit2 = function (i) {
  88285. var t = _this.triangles[i];
  88286. for (var j = 0; j < 3; ++j) {
  88287. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  88288. }
  88289. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88290. };
  88291. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  88292. callback();
  88293. });
  88294. });
  88295. };
  88296. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  88297. var newTriangles = [];
  88298. var i;
  88299. for (i = 0; i < this.vertices.length; ++i) {
  88300. this.vertices[i].triangleCount = 0;
  88301. }
  88302. var t;
  88303. var j;
  88304. for (i = 0; i < this.triangles.length; ++i) {
  88305. if (!this.triangles[i].deleted) {
  88306. t = this.triangles[i];
  88307. for (j = 0; j < 3; ++j) {
  88308. t.vertices[j].triangleCount = 1;
  88309. }
  88310. newTriangles.push(t);
  88311. }
  88312. }
  88313. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  88314. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  88315. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  88316. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  88317. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  88318. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88319. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  88320. var vertexCount = 0;
  88321. for (i = 0; i < this.vertices.length; ++i) {
  88322. var vertex = this.vertices[i];
  88323. vertex.id = vertexCount;
  88324. if (vertex.triangleCount) {
  88325. vertex.originalOffsets.forEach(function (originalOffset) {
  88326. if (!normalData) {
  88327. return;
  88328. }
  88329. newPositionData.push(vertex.position.x);
  88330. newPositionData.push(vertex.position.y);
  88331. newPositionData.push(vertex.position.z);
  88332. newNormalData.push(normalData[originalOffset * 3]);
  88333. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  88334. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  88335. if (uvs && uvs.length) {
  88336. newUVsData.push(uvs[(originalOffset * 2)]);
  88337. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  88338. }
  88339. else if (colorsData && colorsData.length) {
  88340. newColorsData.push(colorsData[(originalOffset * 4)]);
  88341. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  88342. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  88343. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  88344. }
  88345. ++vertexCount;
  88346. });
  88347. }
  88348. }
  88349. var startingIndex = this._reconstructedMesh.getTotalIndices();
  88350. var startingVertex = this._reconstructedMesh.getTotalVertices();
  88351. var submeshesArray = this._reconstructedMesh.subMeshes;
  88352. this._reconstructedMesh.subMeshes = [];
  88353. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  88354. var originalIndices = this._mesh.getIndices();
  88355. for (i = 0; i < newTriangles.length; ++i) {
  88356. t = newTriangles[i]; //now get the new referencing point for each vertex
  88357. [0, 1, 2].forEach(function (idx) {
  88358. var id = originalIndices[t.originalOffset + idx];
  88359. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  88360. if (offset < 0)
  88361. offset = 0;
  88362. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  88363. });
  88364. }
  88365. //overwriting the old vertex buffers and indices.
  88366. this._reconstructedMesh.setIndices(newIndicesArray);
  88367. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  88368. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  88369. if (newUVsData.length > 0)
  88370. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  88371. if (newColorsData.length > 0)
  88372. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  88373. //create submesh
  88374. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  88375. if (submeshIndex > 0) {
  88376. this._reconstructedMesh.subMeshes = [];
  88377. submeshesArray.forEach(function (submesh) {
  88378. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  88379. });
  88380. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  88381. }
  88382. };
  88383. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  88384. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  88385. this._reconstructedMesh.material = this._mesh.material;
  88386. this._reconstructedMesh.parent = this._mesh.parent;
  88387. this._reconstructedMesh.isVisible = false;
  88388. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  88389. };
  88390. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  88391. for (var i = 0; i < vertex1.triangleCount; ++i) {
  88392. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  88393. if (t.deleted)
  88394. continue;
  88395. var s = this.references[vertex1.triangleStart + i].vertexId;
  88396. var v1 = t.vertices[(s + 1) % 3];
  88397. var v2 = t.vertices[(s + 2) % 3];
  88398. if ((v1 === vertex2 || v2 === vertex2)) {
  88399. deletedArray[i] = true;
  88400. delTr.push(t);
  88401. continue;
  88402. }
  88403. var d1 = v1.position.subtract(point);
  88404. d1 = d1.normalize();
  88405. var d2 = v2.position.subtract(point);
  88406. d2 = d2.normalize();
  88407. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  88408. return true;
  88409. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  88410. deletedArray[i] = false;
  88411. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  88412. return true;
  88413. }
  88414. return false;
  88415. };
  88416. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  88417. var newDeleted = deletedTriangles;
  88418. for (var i = 0; i < vertex.triangleCount; ++i) {
  88419. var ref = this.references[vertex.triangleStart + i];
  88420. var t = this.triangles[ref.triangleId];
  88421. if (t.deleted)
  88422. continue;
  88423. if (deletedArray[i] && t.deletePending) {
  88424. t.deleted = true;
  88425. newDeleted++;
  88426. continue;
  88427. }
  88428. t.vertices[ref.vertexId] = origVertex;
  88429. t.isDirty = true;
  88430. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  88431. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  88432. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  88433. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88434. this.references.push(ref);
  88435. }
  88436. return newDeleted;
  88437. };
  88438. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  88439. for (var i = 0; i < this.vertices.length; ++i) {
  88440. var vCount = [];
  88441. var vId = [];
  88442. var v = this.vertices[i];
  88443. var j;
  88444. for (j = 0; j < v.triangleCount; ++j) {
  88445. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  88446. for (var ii = 0; ii < 3; ii++) {
  88447. var ofs = 0;
  88448. var vv = triangle.vertices[ii];
  88449. while (ofs < vCount.length) {
  88450. if (vId[ofs] === vv.id)
  88451. break;
  88452. ++ofs;
  88453. }
  88454. if (ofs === vCount.length) {
  88455. vCount.push(1);
  88456. vId.push(vv.id);
  88457. }
  88458. else {
  88459. vCount[ofs]++;
  88460. }
  88461. }
  88462. }
  88463. for (j = 0; j < vCount.length; ++j) {
  88464. if (vCount[j] === 1) {
  88465. this.vertices[vId[j]].isBorder = true;
  88466. }
  88467. else {
  88468. this.vertices[vId[j]].isBorder = false;
  88469. }
  88470. }
  88471. }
  88472. };
  88473. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  88474. if (identifyBorders === void 0) { identifyBorders = false; }
  88475. var i;
  88476. if (!identifyBorders) {
  88477. var newTrianglesVector = [];
  88478. for (i = 0; i < this.triangles.length; ++i) {
  88479. if (!this.triangles[i].deleted) {
  88480. newTrianglesVector.push(this.triangles[i]);
  88481. }
  88482. }
  88483. this.triangles = newTrianglesVector;
  88484. }
  88485. for (i = 0; i < this.vertices.length; ++i) {
  88486. this.vertices[i].triangleCount = 0;
  88487. this.vertices[i].triangleStart = 0;
  88488. }
  88489. var t;
  88490. var j;
  88491. var v;
  88492. for (i = 0; i < this.triangles.length; ++i) {
  88493. t = this.triangles[i];
  88494. for (j = 0; j < 3; ++j) {
  88495. v = t.vertices[j];
  88496. v.triangleCount++;
  88497. }
  88498. }
  88499. var tStart = 0;
  88500. for (i = 0; i < this.vertices.length; ++i) {
  88501. this.vertices[i].triangleStart = tStart;
  88502. tStart += this.vertices[i].triangleCount;
  88503. this.vertices[i].triangleCount = 0;
  88504. }
  88505. var newReferences = new Array(this.triangles.length * 3);
  88506. for (i = 0; i < this.triangles.length; ++i) {
  88507. t = this.triangles[i];
  88508. for (j = 0; j < 3; ++j) {
  88509. v = t.vertices[j];
  88510. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  88511. v.triangleCount++;
  88512. }
  88513. }
  88514. this.references = newReferences;
  88515. if (identifyBorders) {
  88516. this.identifyBorder();
  88517. }
  88518. };
  88519. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  88520. var x = point.x;
  88521. var y = point.y;
  88522. var z = point.z;
  88523. 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
  88524. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  88525. };
  88526. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  88527. var q = vertex1.q.add(vertex2.q);
  88528. var border = vertex1.isBorder && vertex2.isBorder;
  88529. var error = 0;
  88530. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  88531. if (qDet !== 0 && !border) {
  88532. if (!pointResult) {
  88533. pointResult = BABYLON.Vector3.Zero();
  88534. }
  88535. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  88536. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  88537. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  88538. error = this.vertexError(q, pointResult);
  88539. }
  88540. else {
  88541. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  88542. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  88543. var error1 = this.vertexError(q, vertex1.position);
  88544. var error2 = this.vertexError(q, vertex2.position);
  88545. var error3 = this.vertexError(q, p3);
  88546. error = Math.min(error1, error2, error3);
  88547. if (error === error1) {
  88548. if (pointResult) {
  88549. pointResult.copyFrom(vertex1.position);
  88550. }
  88551. }
  88552. else if (error === error2) {
  88553. if (pointResult) {
  88554. pointResult.copyFrom(vertex2.position);
  88555. }
  88556. }
  88557. else {
  88558. if (pointResult) {
  88559. pointResult.copyFrom(p3);
  88560. }
  88561. }
  88562. }
  88563. return error;
  88564. };
  88565. return QuadraticErrorSimplification;
  88566. }());
  88567. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  88568. })(BABYLON || (BABYLON = {}));
  88569. //# sourceMappingURL=babylon.meshSimplification.js.map
  88570. "use strict";
  88571. var BABYLON;
  88572. (function (BABYLON) {
  88573. var MeshLODLevel = /** @class */ (function () {
  88574. function MeshLODLevel(distance, mesh) {
  88575. this.distance = distance;
  88576. this.mesh = mesh;
  88577. }
  88578. return MeshLODLevel;
  88579. }());
  88580. BABYLON.MeshLODLevel = MeshLODLevel;
  88581. })(BABYLON || (BABYLON = {}));
  88582. //# sourceMappingURL=babylon.meshLODLevel.js.map
  88583. "use strict";
  88584. var BABYLON;
  88585. (function (BABYLON) {
  88586. /**
  88587. * Defines the root class used to create scene optimization to use with SceneOptimizer
  88588. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88589. */
  88590. var SceneOptimization = /** @class */ (function () {
  88591. /**
  88592. * Creates the SceneOptimization object
  88593. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88594. * @param desc defines the description associated with the optimization
  88595. */
  88596. function SceneOptimization(
  88597. /**
  88598. * Defines the priority of this optimization (0 by default which means first in the list)
  88599. */
  88600. priority) {
  88601. if (priority === void 0) { priority = 0; }
  88602. this.priority = priority;
  88603. }
  88604. /**
  88605. * Gets a string describing the action executed by the current optimization
  88606. * @returns description string
  88607. */
  88608. SceneOptimization.prototype.getDescription = function () {
  88609. return "";
  88610. };
  88611. /**
  88612. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88613. * @param scene defines the current scene where to apply this optimization
  88614. * @param optimizer defines the current optimizer
  88615. * @returns true if everything that can be done was applied
  88616. */
  88617. SceneOptimization.prototype.apply = function (scene, optimizer) {
  88618. return true;
  88619. };
  88620. ;
  88621. return SceneOptimization;
  88622. }());
  88623. BABYLON.SceneOptimization = SceneOptimization;
  88624. /**
  88625. * Defines an optimization used to reduce the size of render target textures
  88626. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88627. */
  88628. var TextureOptimization = /** @class */ (function (_super) {
  88629. __extends(TextureOptimization, _super);
  88630. /**
  88631. * Creates the TextureOptimization object
  88632. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88633. * @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
  88634. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88635. */
  88636. function TextureOptimization(
  88637. /**
  88638. * Defines the priority of this optimization (0 by default which means first in the list)
  88639. */
  88640. priority,
  88641. /**
  88642. * 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
  88643. */
  88644. maximumSize,
  88645. /**
  88646. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  88647. */
  88648. step) {
  88649. if (priority === void 0) { priority = 0; }
  88650. if (maximumSize === void 0) { maximumSize = 1024; }
  88651. if (step === void 0) { step = 0.5; }
  88652. var _this = _super.call(this, priority) || this;
  88653. _this.priority = priority;
  88654. _this.maximumSize = maximumSize;
  88655. _this.step = step;
  88656. return _this;
  88657. }
  88658. /**
  88659. * Gets a string describing the action executed by the current optimization
  88660. * @returns description string
  88661. */
  88662. TextureOptimization.prototype.getDescription = function () {
  88663. return "Reducing render target texture size to " + this.maximumSize;
  88664. };
  88665. /**
  88666. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88667. * @param scene defines the current scene where to apply this optimization
  88668. * @param optimizer defines the current optimizer
  88669. * @returns true if everything that can be done was applied
  88670. */
  88671. TextureOptimization.prototype.apply = function (scene, optimizer) {
  88672. var allDone = true;
  88673. for (var index = 0; index < scene.textures.length; index++) {
  88674. var texture = scene.textures[index];
  88675. if (!texture.canRescale || texture.getContext) {
  88676. continue;
  88677. }
  88678. var currentSize = texture.getSize();
  88679. var maxDimension = Math.max(currentSize.width, currentSize.height);
  88680. if (maxDimension > this.maximumSize) {
  88681. texture.scale(this.step);
  88682. allDone = false;
  88683. }
  88684. }
  88685. return allDone;
  88686. };
  88687. return TextureOptimization;
  88688. }(SceneOptimization));
  88689. BABYLON.TextureOptimization = TextureOptimization;
  88690. /**
  88691. * Defines an optimization used to increase or decrease the rendering resolution
  88692. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88693. */
  88694. var HardwareScalingOptimization = /** @class */ (function (_super) {
  88695. __extends(HardwareScalingOptimization, _super);
  88696. /**
  88697. * Creates the HardwareScalingOptimization object
  88698. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88699. * @param maximumScale defines the maximum scale to use (2 by default)
  88700. * @param step defines the step to use between two passes (0.5 by default)
  88701. */
  88702. function HardwareScalingOptimization(
  88703. /**
  88704. * Defines the priority of this optimization (0 by default which means first in the list)
  88705. */
  88706. priority,
  88707. /**
  88708. * Defines the maximum scale to use (2 by default)
  88709. */
  88710. maximumScale,
  88711. /**
  88712. * Defines the step to use between two passes (0.5 by default)
  88713. */
  88714. step) {
  88715. if (priority === void 0) { priority = 0; }
  88716. if (maximumScale === void 0) { maximumScale = 2; }
  88717. if (step === void 0) { step = 0.25; }
  88718. var _this = _super.call(this, priority) || this;
  88719. _this.priority = priority;
  88720. _this.maximumScale = maximumScale;
  88721. _this.step = step;
  88722. _this._currentScale = -1;
  88723. _this._directionOffset = 1;
  88724. return _this;
  88725. }
  88726. /**
  88727. * Gets a string describing the action executed by the current optimization
  88728. * @return description string
  88729. */
  88730. HardwareScalingOptimization.prototype.getDescription = function () {
  88731. return "Setting hardware scaling level to " + this._currentScale;
  88732. };
  88733. /**
  88734. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88735. * @param scene defines the current scene where to apply this optimization
  88736. * @param optimizer defines the current optimizer
  88737. * @returns true if everything that can be done was applied
  88738. */
  88739. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  88740. if (this._currentScale === -1) {
  88741. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  88742. if (this._currentScale > this.maximumScale) {
  88743. this._directionOffset = -1;
  88744. }
  88745. }
  88746. this._currentScale += this._directionOffset * this.step;
  88747. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  88748. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  88749. };
  88750. ;
  88751. return HardwareScalingOptimization;
  88752. }(SceneOptimization));
  88753. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  88754. /**
  88755. * Defines an optimization used to remove shadows
  88756. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88757. */
  88758. var ShadowsOptimization = /** @class */ (function (_super) {
  88759. __extends(ShadowsOptimization, _super);
  88760. function ShadowsOptimization() {
  88761. return _super !== null && _super.apply(this, arguments) || this;
  88762. }
  88763. /**
  88764. * Gets a string describing the action executed by the current optimization
  88765. * @return description string
  88766. */
  88767. ShadowsOptimization.prototype.getDescription = function () {
  88768. return "Turning shadows on/off";
  88769. };
  88770. /**
  88771. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88772. * @param scene defines the current scene where to apply this optimization
  88773. * @param optimizer defines the current optimizer
  88774. * @returns true if everything that can be done was applied
  88775. */
  88776. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  88777. scene.shadowsEnabled = optimizer.isInImprovementMode;
  88778. return true;
  88779. };
  88780. ;
  88781. return ShadowsOptimization;
  88782. }(SceneOptimization));
  88783. BABYLON.ShadowsOptimization = ShadowsOptimization;
  88784. /**
  88785. * Defines an optimization used to turn post-processes off
  88786. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88787. */
  88788. var PostProcessesOptimization = /** @class */ (function (_super) {
  88789. __extends(PostProcessesOptimization, _super);
  88790. function PostProcessesOptimization() {
  88791. return _super !== null && _super.apply(this, arguments) || this;
  88792. }
  88793. /**
  88794. * Gets a string describing the action executed by the current optimization
  88795. * @return description string
  88796. */
  88797. PostProcessesOptimization.prototype.getDescription = function () {
  88798. return "Turning post-processes on/off";
  88799. };
  88800. /**
  88801. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88802. * @param scene defines the current scene where to apply this optimization
  88803. * @param optimizer defines the current optimizer
  88804. * @returns true if everything that can be done was applied
  88805. */
  88806. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  88807. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  88808. return true;
  88809. };
  88810. ;
  88811. return PostProcessesOptimization;
  88812. }(SceneOptimization));
  88813. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  88814. /**
  88815. * Defines an optimization used to turn lens flares off
  88816. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88817. */
  88818. var LensFlaresOptimization = /** @class */ (function (_super) {
  88819. __extends(LensFlaresOptimization, _super);
  88820. function LensFlaresOptimization() {
  88821. return _super !== null && _super.apply(this, arguments) || this;
  88822. }
  88823. /**
  88824. * Gets a string describing the action executed by the current optimization
  88825. * @return description string
  88826. */
  88827. LensFlaresOptimization.prototype.getDescription = function () {
  88828. return "Turning lens flares on/off";
  88829. };
  88830. /**
  88831. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88832. * @param scene defines the current scene where to apply this optimization
  88833. * @param optimizer defines the current optimizer
  88834. * @returns true if everything that can be done was applied
  88835. */
  88836. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  88837. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  88838. return true;
  88839. };
  88840. ;
  88841. return LensFlaresOptimization;
  88842. }(SceneOptimization));
  88843. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  88844. /**
  88845. * Defines an optimization based on user defined callback.
  88846. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88847. */
  88848. var CustomOptimization = /** @class */ (function (_super) {
  88849. __extends(CustomOptimization, _super);
  88850. function CustomOptimization() {
  88851. return _super !== null && _super.apply(this, arguments) || this;
  88852. }
  88853. /**
  88854. * Gets a string describing the action executed by the current optimization
  88855. * @returns description string
  88856. */
  88857. CustomOptimization.prototype.getDescription = function () {
  88858. if (this.onGetDescription) {
  88859. return this.onGetDescription();
  88860. }
  88861. return "Running user defined callback";
  88862. };
  88863. /**
  88864. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88865. * @param scene defines the current scene where to apply this optimization
  88866. * @param optimizer defines the current optimizer
  88867. * @returns true if everything that can be done was applied
  88868. */
  88869. CustomOptimization.prototype.apply = function (scene, optimizer) {
  88870. if (this.onApply) {
  88871. return this.onApply(scene, optimizer);
  88872. }
  88873. return true;
  88874. };
  88875. ;
  88876. return CustomOptimization;
  88877. }(SceneOptimization));
  88878. BABYLON.CustomOptimization = CustomOptimization;
  88879. /**
  88880. * Defines an optimization used to turn particles off
  88881. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88882. */
  88883. var ParticlesOptimization = /** @class */ (function (_super) {
  88884. __extends(ParticlesOptimization, _super);
  88885. function ParticlesOptimization() {
  88886. return _super !== null && _super.apply(this, arguments) || this;
  88887. }
  88888. /**
  88889. * Gets a string describing the action executed by the current optimization
  88890. * @return description string
  88891. */
  88892. ParticlesOptimization.prototype.getDescription = function () {
  88893. return "Turning particles on/off";
  88894. };
  88895. /**
  88896. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88897. * @param scene defines the current scene where to apply this optimization
  88898. * @param optimizer defines the current optimizer
  88899. * @returns true if everything that can be done was applied
  88900. */
  88901. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  88902. scene.particlesEnabled = optimizer.isInImprovementMode;
  88903. return true;
  88904. };
  88905. ;
  88906. return ParticlesOptimization;
  88907. }(SceneOptimization));
  88908. BABYLON.ParticlesOptimization = ParticlesOptimization;
  88909. /**
  88910. * Defines an optimization used to turn render targets off
  88911. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88912. */
  88913. var RenderTargetsOptimization = /** @class */ (function (_super) {
  88914. __extends(RenderTargetsOptimization, _super);
  88915. function RenderTargetsOptimization() {
  88916. return _super !== null && _super.apply(this, arguments) || this;
  88917. }
  88918. /**
  88919. * Gets a string describing the action executed by the current optimization
  88920. * @return description string
  88921. */
  88922. RenderTargetsOptimization.prototype.getDescription = function () {
  88923. return "Turning render targets off";
  88924. };
  88925. /**
  88926. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88927. * @param scene defines the current scene where to apply this optimization
  88928. * @param optimizer defines the current optimizer
  88929. * @returns true if everything that can be done was applied
  88930. */
  88931. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  88932. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  88933. return true;
  88934. };
  88935. ;
  88936. return RenderTargetsOptimization;
  88937. }(SceneOptimization));
  88938. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  88939. /**
  88940. * Defines an optimization used to merge meshes with compatible materials
  88941. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88942. */
  88943. var MergeMeshesOptimization = /** @class */ (function (_super) {
  88944. __extends(MergeMeshesOptimization, _super);
  88945. function MergeMeshesOptimization() {
  88946. var _this = _super !== null && _super.apply(this, arguments) || this;
  88947. _this._canBeMerged = function (abstractMesh) {
  88948. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  88949. return false;
  88950. }
  88951. var mesh = abstractMesh;
  88952. if (!mesh.isVisible || !mesh.isEnabled()) {
  88953. return false;
  88954. }
  88955. if (mesh.instances.length > 0) {
  88956. return false;
  88957. }
  88958. if (mesh.skeleton || mesh.hasLODLevels) {
  88959. return false;
  88960. }
  88961. if (mesh.parent) {
  88962. return false;
  88963. }
  88964. return true;
  88965. };
  88966. return _this;
  88967. }
  88968. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  88969. /**
  88970. * Gets or sets a boolean which defines if optimization octree has to be updated
  88971. */
  88972. get: function () {
  88973. return MergeMeshesOptimization._UpdateSelectionTree;
  88974. },
  88975. /**
  88976. * Gets or sets a boolean which defines if optimization octree has to be updated
  88977. */
  88978. set: function (value) {
  88979. MergeMeshesOptimization._UpdateSelectionTree = value;
  88980. },
  88981. enumerable: true,
  88982. configurable: true
  88983. });
  88984. /**
  88985. * Gets a string describing the action executed by the current optimization
  88986. * @return description string
  88987. */
  88988. MergeMeshesOptimization.prototype.getDescription = function () {
  88989. return "Merging similar meshes together";
  88990. };
  88991. /**
  88992. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88993. * @param scene defines the current scene where to apply this optimization
  88994. * @param optimizer defines the current optimizer
  88995. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  88996. * @returns true if everything that can be done was applied
  88997. */
  88998. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  88999. var globalPool = scene.meshes.slice(0);
  89000. var globalLength = globalPool.length;
  89001. for (var index = 0; index < globalLength; index++) {
  89002. var currentPool = new Array();
  89003. var current = globalPool[index];
  89004. // Checks
  89005. if (!this._canBeMerged(current)) {
  89006. continue;
  89007. }
  89008. currentPool.push(current);
  89009. // Find compatible meshes
  89010. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  89011. var otherMesh = globalPool[subIndex];
  89012. if (!this._canBeMerged(otherMesh)) {
  89013. continue;
  89014. }
  89015. if (otherMesh.material !== current.material) {
  89016. continue;
  89017. }
  89018. if (otherMesh.checkCollisions !== current.checkCollisions) {
  89019. continue;
  89020. }
  89021. currentPool.push(otherMesh);
  89022. globalLength--;
  89023. globalPool.splice(subIndex, 1);
  89024. subIndex--;
  89025. }
  89026. if (currentPool.length < 2) {
  89027. continue;
  89028. }
  89029. // Merge meshes
  89030. BABYLON.Mesh.MergeMeshes(currentPool);
  89031. }
  89032. if (updateSelectionTree != undefined) {
  89033. if (updateSelectionTree) {
  89034. scene.createOrUpdateSelectionOctree();
  89035. }
  89036. }
  89037. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  89038. scene.createOrUpdateSelectionOctree();
  89039. }
  89040. return true;
  89041. };
  89042. ;
  89043. MergeMeshesOptimization._UpdateSelectionTree = false;
  89044. return MergeMeshesOptimization;
  89045. }(SceneOptimization));
  89046. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  89047. /**
  89048. * Defines a list of options used by SceneOptimizer
  89049. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89050. */
  89051. var SceneOptimizerOptions = /** @class */ (function () {
  89052. /**
  89053. * Creates a new list of options used by SceneOptimizer
  89054. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  89055. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  89056. */
  89057. function SceneOptimizerOptions(
  89058. /**
  89059. * Defines the target frame rate to reach (60 by default)
  89060. */
  89061. targetFrameRate,
  89062. /**
  89063. * Defines the interval between two checkes (2000ms by default)
  89064. */
  89065. trackerDuration) {
  89066. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  89067. if (trackerDuration === void 0) { trackerDuration = 2000; }
  89068. this.targetFrameRate = targetFrameRate;
  89069. this.trackerDuration = trackerDuration;
  89070. /**
  89071. * Gets the list of optimizations to apply
  89072. */
  89073. this.optimizations = new Array();
  89074. }
  89075. /**
  89076. * Add a new optimization
  89077. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  89078. * @returns the current SceneOptimizerOptions
  89079. */
  89080. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  89081. this.optimizations.push(optimization);
  89082. return this;
  89083. };
  89084. /**
  89085. * Add a new custom optimization
  89086. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  89087. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  89088. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89089. * @returns the current SceneOptimizerOptions
  89090. */
  89091. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  89092. if (priority === void 0) { priority = 0; }
  89093. var optimization = new CustomOptimization(priority);
  89094. optimization.onApply = onApply;
  89095. optimization.onGetDescription = onGetDescription;
  89096. this.optimizations.push(optimization);
  89097. return this;
  89098. };
  89099. /**
  89100. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  89101. * @param targetFrameRate defines the target frame rate (60 by default)
  89102. * @returns a SceneOptimizerOptions object
  89103. */
  89104. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  89105. var result = new SceneOptimizerOptions(targetFrameRate);
  89106. var priority = 0;
  89107. result.addOptimization(new MergeMeshesOptimization(priority));
  89108. result.addOptimization(new ShadowsOptimization(priority));
  89109. result.addOptimization(new LensFlaresOptimization(priority));
  89110. // Next priority
  89111. priority++;
  89112. result.addOptimization(new PostProcessesOptimization(priority));
  89113. result.addOptimization(new ParticlesOptimization(priority));
  89114. // Next priority
  89115. priority++;
  89116. result.addOptimization(new TextureOptimization(priority, 1024));
  89117. return result;
  89118. };
  89119. /**
  89120. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  89121. * @param targetFrameRate defines the target frame rate (60 by default)
  89122. * @returns a SceneOptimizerOptions object
  89123. */
  89124. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  89125. var result = new SceneOptimizerOptions(targetFrameRate);
  89126. var priority = 0;
  89127. result.addOptimization(new MergeMeshesOptimization(priority));
  89128. result.addOptimization(new ShadowsOptimization(priority));
  89129. result.addOptimization(new LensFlaresOptimization(priority));
  89130. // Next priority
  89131. priority++;
  89132. result.addOptimization(new PostProcessesOptimization(priority));
  89133. result.addOptimization(new ParticlesOptimization(priority));
  89134. // Next priority
  89135. priority++;
  89136. result.addOptimization(new TextureOptimization(priority, 512));
  89137. // Next priority
  89138. priority++;
  89139. result.addOptimization(new RenderTargetsOptimization(priority));
  89140. // Next priority
  89141. priority++;
  89142. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  89143. return result;
  89144. };
  89145. /**
  89146. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  89147. * @param targetFrameRate defines the target frame rate (60 by default)
  89148. * @returns a SceneOptimizerOptions object
  89149. */
  89150. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  89151. var result = new SceneOptimizerOptions(targetFrameRate);
  89152. var priority = 0;
  89153. result.addOptimization(new MergeMeshesOptimization(priority));
  89154. result.addOptimization(new ShadowsOptimization(priority));
  89155. result.addOptimization(new LensFlaresOptimization(priority));
  89156. // Next priority
  89157. priority++;
  89158. result.addOptimization(new PostProcessesOptimization(priority));
  89159. result.addOptimization(new ParticlesOptimization(priority));
  89160. // Next priority
  89161. priority++;
  89162. result.addOptimization(new TextureOptimization(priority, 256));
  89163. // Next priority
  89164. priority++;
  89165. result.addOptimization(new RenderTargetsOptimization(priority));
  89166. // Next priority
  89167. priority++;
  89168. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  89169. return result;
  89170. };
  89171. return SceneOptimizerOptions;
  89172. }());
  89173. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  89174. /**
  89175. * Class used to run optimizations in order to reach a target frame rate
  89176. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89177. */
  89178. var SceneOptimizer = /** @class */ (function () {
  89179. /**
  89180. * Creates a new SceneOptimizer
  89181. * @param scene defines the scene to work on
  89182. * @param options defines the options to use with the SceneOptimizer
  89183. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  89184. * @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)
  89185. */
  89186. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  89187. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  89188. if (improvementMode === void 0) { improvementMode = false; }
  89189. var _this = this;
  89190. this._isRunning = false;
  89191. this._currentPriorityLevel = 0;
  89192. this._targetFrameRate = 60;
  89193. this._trackerDuration = 2000;
  89194. this._currentFrameRate = 0;
  89195. this._improvementMode = false;
  89196. /**
  89197. * Defines an observable called when the optimizer reaches the target frame rate
  89198. */
  89199. this.onSuccessObservable = new BABYLON.Observable();
  89200. /**
  89201. * Defines an observable called when the optimizer enables an optimization
  89202. */
  89203. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89204. /**
  89205. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89206. */
  89207. this.onFailureObservable = new BABYLON.Observable();
  89208. if (!options) {
  89209. this._options = new SceneOptimizerOptions();
  89210. }
  89211. else {
  89212. this._options = options;
  89213. }
  89214. if (this._options.targetFrameRate) {
  89215. this._targetFrameRate = this._options.targetFrameRate;
  89216. }
  89217. if (this._options.trackerDuration) {
  89218. this._trackerDuration = this._options.trackerDuration;
  89219. }
  89220. if (autoGeneratePriorities) {
  89221. var priority = 0;
  89222. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89223. var optim = _a[_i];
  89224. optim.priority = priority++;
  89225. }
  89226. }
  89227. this._improvementMode = improvementMode;
  89228. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89229. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89230. _this._sceneDisposeObserver = null;
  89231. _this.dispose();
  89232. });
  89233. }
  89234. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89235. /**
  89236. * Gets a boolean indicating if the optimizer is in improvement mode
  89237. */
  89238. get: function () {
  89239. return this._improvementMode;
  89240. },
  89241. enumerable: true,
  89242. configurable: true
  89243. });
  89244. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89245. /**
  89246. * Gets the current priority level (0 at start)
  89247. */
  89248. get: function () {
  89249. return this._currentPriorityLevel;
  89250. },
  89251. enumerable: true,
  89252. configurable: true
  89253. });
  89254. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89255. /**
  89256. * Gets the current frame rate checked by the SceneOptimizer
  89257. */
  89258. get: function () {
  89259. return this._currentFrameRate;
  89260. },
  89261. enumerable: true,
  89262. configurable: true
  89263. });
  89264. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  89265. /**
  89266. * Gets or sets the current target frame rate (60 by default)
  89267. */
  89268. get: function () {
  89269. return this._targetFrameRate;
  89270. },
  89271. /**
  89272. * Gets or sets the current target frame rate (60 by default)
  89273. */
  89274. set: function (value) {
  89275. this._targetFrameRate = value;
  89276. },
  89277. enumerable: true,
  89278. configurable: true
  89279. });
  89280. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  89281. /**
  89282. * Gets or sets the current interval between two checks (every 2000ms by default)
  89283. */
  89284. get: function () {
  89285. return this._trackerDuration;
  89286. },
  89287. /**
  89288. * Gets or sets the current interval between two checks (every 2000ms by default)
  89289. */
  89290. set: function (value) {
  89291. this._trackerDuration = value;
  89292. },
  89293. enumerable: true,
  89294. configurable: true
  89295. });
  89296. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  89297. /**
  89298. * Gets the list of active optimizations
  89299. */
  89300. get: function () {
  89301. return this._options.optimizations;
  89302. },
  89303. enumerable: true,
  89304. configurable: true
  89305. });
  89306. /**
  89307. * Stops the current optimizer
  89308. */
  89309. SceneOptimizer.prototype.stop = function () {
  89310. this._isRunning = false;
  89311. };
  89312. /**
  89313. * Reset the optimizer to initial step (current priority level = 0)
  89314. */
  89315. SceneOptimizer.prototype.reset = function () {
  89316. this._currentPriorityLevel = 0;
  89317. };
  89318. /**
  89319. * Start the optimizer. By default it will try to reach a specific framerate
  89320. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  89321. */
  89322. SceneOptimizer.prototype.start = function () {
  89323. var _this = this;
  89324. if (this._isRunning) {
  89325. return;
  89326. }
  89327. this._isRunning = true;
  89328. // Let's wait for the scene to be ready before running our check
  89329. this._scene.executeWhenReady(function () {
  89330. setTimeout(function () {
  89331. _this._checkCurrentState();
  89332. }, _this._trackerDuration);
  89333. });
  89334. };
  89335. SceneOptimizer.prototype._checkCurrentState = function () {
  89336. var _this = this;
  89337. if (!this._isRunning) {
  89338. return;
  89339. }
  89340. var scene = this._scene;
  89341. var options = this._options;
  89342. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  89343. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  89344. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  89345. this._isRunning = false;
  89346. this.onSuccessObservable.notifyObservers(this);
  89347. return;
  89348. }
  89349. // Apply current level of optimizations
  89350. var allDone = true;
  89351. var noOptimizationApplied = true;
  89352. for (var index = 0; index < options.optimizations.length; index++) {
  89353. var optimization = options.optimizations[index];
  89354. if (optimization.priority === this._currentPriorityLevel) {
  89355. noOptimizationApplied = false;
  89356. allDone = allDone && optimization.apply(scene, this);
  89357. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  89358. }
  89359. }
  89360. // If no optimization was applied, this is a failure :(
  89361. if (noOptimizationApplied) {
  89362. this._isRunning = false;
  89363. this.onFailureObservable.notifyObservers(this);
  89364. return;
  89365. }
  89366. // If all optimizations were done, move to next level
  89367. if (allDone) {
  89368. this._currentPriorityLevel++;
  89369. }
  89370. // Let's the system running for a specific amount of time before checking FPS
  89371. scene.executeWhenReady(function () {
  89372. setTimeout(function () {
  89373. _this._checkCurrentState();
  89374. }, _this._trackerDuration);
  89375. });
  89376. };
  89377. /**
  89378. * Release all resources
  89379. */
  89380. SceneOptimizer.prototype.dispose = function () {
  89381. this.stop();
  89382. this.onSuccessObservable.clear();
  89383. this.onFailureObservable.clear();
  89384. this.onNewOptimizationAppliedObservable.clear();
  89385. if (this._sceneDisposeObserver) {
  89386. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89387. }
  89388. };
  89389. /**
  89390. * Helper function to create a SceneOptimizer with one single line of code
  89391. * @param scene defines the scene to work on
  89392. * @param options defines the options to use with the SceneOptimizer
  89393. * @param onSuccess defines a callback to call on success
  89394. * @param onFailure defines a callback to call on failure
  89395. * @returns the new SceneOptimizer object
  89396. */
  89397. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  89398. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  89399. if (onSuccess) {
  89400. optimizer.onSuccessObservable.add(function () {
  89401. onSuccess();
  89402. });
  89403. }
  89404. if (onFailure) {
  89405. optimizer.onFailureObservable.add(function () {
  89406. onFailure();
  89407. });
  89408. }
  89409. optimizer.start();
  89410. return optimizer;
  89411. };
  89412. return SceneOptimizer;
  89413. }());
  89414. BABYLON.SceneOptimizer = SceneOptimizer;
  89415. })(BABYLON || (BABYLON = {}));
  89416. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  89417. "use strict";
  89418. var BABYLON;
  89419. (function (BABYLON) {
  89420. var OutlineRenderer = /** @class */ (function () {
  89421. function OutlineRenderer(scene) {
  89422. this.zOffset = 1;
  89423. this._scene = scene;
  89424. }
  89425. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  89426. var _this = this;
  89427. if (useOverlay === void 0) { useOverlay = false; }
  89428. var scene = this._scene;
  89429. var engine = this._scene.getEngine();
  89430. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89431. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  89432. return;
  89433. }
  89434. var mesh = subMesh.getRenderingMesh();
  89435. var material = subMesh.getMaterial();
  89436. if (!material || !scene.activeCamera) {
  89437. return;
  89438. }
  89439. engine.enableEffect(this._effect);
  89440. // Logarithmic depth
  89441. if (material.useLogarithmicDepth) {
  89442. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  89443. }
  89444. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  89445. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  89446. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  89447. // Bones
  89448. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89449. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89450. }
  89451. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  89452. // Alpha test
  89453. if (material && material.needAlphaTesting()) {
  89454. var alphaTexture = material.getAlphaTestTexture();
  89455. if (alphaTexture) {
  89456. this._effect.setTexture("diffuseSampler", alphaTexture);
  89457. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89458. }
  89459. }
  89460. engine.setZOffset(-this.zOffset);
  89461. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  89462. engine.setZOffset(0);
  89463. };
  89464. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  89465. var defines = [];
  89466. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  89467. var mesh = subMesh.getMesh();
  89468. var material = subMesh.getMaterial();
  89469. if (material) {
  89470. // Alpha test
  89471. if (material.needAlphaTesting()) {
  89472. defines.push("#define ALPHATEST");
  89473. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89474. attribs.push(BABYLON.VertexBuffer.UVKind);
  89475. defines.push("#define UV1");
  89476. }
  89477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  89478. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89479. defines.push("#define UV2");
  89480. }
  89481. }
  89482. //Logarithmic depth
  89483. if (material.useLogarithmicDepth) {
  89484. defines.push("#define LOGARITHMICDEPTH");
  89485. }
  89486. }
  89487. // Bones
  89488. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89489. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89490. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89491. if (mesh.numBoneInfluencers > 4) {
  89492. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89493. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89494. }
  89495. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89496. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  89497. }
  89498. else {
  89499. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89500. }
  89501. // Instances
  89502. if (useInstances) {
  89503. defines.push("#define INSTANCES");
  89504. attribs.push("world0");
  89505. attribs.push("world1");
  89506. attribs.push("world2");
  89507. attribs.push("world3");
  89508. }
  89509. // Get correct effect
  89510. var join = defines.join("\n");
  89511. if (this._cachedDefines !== join) {
  89512. this._cachedDefines = join;
  89513. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  89514. }
  89515. return this._effect.isReady();
  89516. };
  89517. return OutlineRenderer;
  89518. }());
  89519. BABYLON.OutlineRenderer = OutlineRenderer;
  89520. })(BABYLON || (BABYLON = {}));
  89521. //# sourceMappingURL=babylon.outlineRenderer.js.map
  89522. "use strict";
  89523. var BABYLON;
  89524. (function (BABYLON) {
  89525. var FaceAdjacencies = /** @class */ (function () {
  89526. function FaceAdjacencies() {
  89527. this.edges = new Array();
  89528. this.edgesConnectedCount = 0;
  89529. }
  89530. return FaceAdjacencies;
  89531. }());
  89532. var EdgesRenderer = /** @class */ (function () {
  89533. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  89534. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  89535. if (epsilon === void 0) { epsilon = 0.95; }
  89536. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  89537. this.edgesWidthScalerForOrthographic = 1000.0;
  89538. this.edgesWidthScalerForPerspective = 50.0;
  89539. this._linesPositions = new Array();
  89540. this._linesNormals = new Array();
  89541. this._linesIndices = new Array();
  89542. this._buffers = {};
  89543. this._checkVerticesInsteadOfIndices = false;
  89544. this._source = source;
  89545. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  89546. this._epsilon = epsilon;
  89547. this._prepareRessources();
  89548. this._generateEdgesLines();
  89549. }
  89550. EdgesRenderer.prototype._prepareRessources = function () {
  89551. if (this._lineShader) {
  89552. return;
  89553. }
  89554. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  89555. attributes: ["position", "normal"],
  89556. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  89557. });
  89558. this._lineShader.disableDepthWrite = true;
  89559. this._lineShader.backFaceCulling = false;
  89560. };
  89561. EdgesRenderer.prototype._rebuild = function () {
  89562. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89563. if (buffer) {
  89564. buffer._rebuild();
  89565. }
  89566. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89567. if (buffer) {
  89568. buffer._rebuild();
  89569. }
  89570. var scene = this._source.getScene();
  89571. var engine = scene.getEngine();
  89572. this._ib = engine.createIndexBuffer(this._linesIndices);
  89573. };
  89574. EdgesRenderer.prototype.dispose = function () {
  89575. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  89576. if (buffer) {
  89577. buffer.dispose();
  89578. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  89579. }
  89580. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  89581. if (buffer) {
  89582. buffer.dispose();
  89583. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  89584. }
  89585. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  89586. this._lineShader.dispose();
  89587. };
  89588. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  89589. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  89590. return 0;
  89591. }
  89592. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  89593. return 1;
  89594. }
  89595. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  89596. return 2;
  89597. }
  89598. return -1;
  89599. };
  89600. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  89601. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  89602. return 0;
  89603. }
  89604. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  89605. return 1;
  89606. }
  89607. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  89608. return 2;
  89609. }
  89610. return -1;
  89611. };
  89612. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  89613. var needToCreateLine;
  89614. if (edge === undefined) {
  89615. needToCreateLine = true;
  89616. }
  89617. else {
  89618. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  89619. needToCreateLine = dotProduct < this._epsilon;
  89620. }
  89621. if (needToCreateLine) {
  89622. var offset = this._linesPositions.length / 3;
  89623. var normal = p0.subtract(p1);
  89624. normal.normalize();
  89625. // Positions
  89626. this._linesPositions.push(p0.x);
  89627. this._linesPositions.push(p0.y);
  89628. this._linesPositions.push(p0.z);
  89629. this._linesPositions.push(p0.x);
  89630. this._linesPositions.push(p0.y);
  89631. this._linesPositions.push(p0.z);
  89632. this._linesPositions.push(p1.x);
  89633. this._linesPositions.push(p1.y);
  89634. this._linesPositions.push(p1.z);
  89635. this._linesPositions.push(p1.x);
  89636. this._linesPositions.push(p1.y);
  89637. this._linesPositions.push(p1.z);
  89638. // Normals
  89639. this._linesNormals.push(p1.x);
  89640. this._linesNormals.push(p1.y);
  89641. this._linesNormals.push(p1.z);
  89642. this._linesNormals.push(-1);
  89643. this._linesNormals.push(p1.x);
  89644. this._linesNormals.push(p1.y);
  89645. this._linesNormals.push(p1.z);
  89646. this._linesNormals.push(1);
  89647. this._linesNormals.push(p0.x);
  89648. this._linesNormals.push(p0.y);
  89649. this._linesNormals.push(p0.z);
  89650. this._linesNormals.push(-1);
  89651. this._linesNormals.push(p0.x);
  89652. this._linesNormals.push(p0.y);
  89653. this._linesNormals.push(p0.z);
  89654. this._linesNormals.push(1);
  89655. // Indices
  89656. this._linesIndices.push(offset);
  89657. this._linesIndices.push(offset + 1);
  89658. this._linesIndices.push(offset + 2);
  89659. this._linesIndices.push(offset);
  89660. this._linesIndices.push(offset + 2);
  89661. this._linesIndices.push(offset + 3);
  89662. }
  89663. };
  89664. EdgesRenderer.prototype._generateEdgesLines = function () {
  89665. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89666. var indices = this._source.getIndices();
  89667. if (!indices || !positions) {
  89668. return;
  89669. }
  89670. // First let's find adjacencies
  89671. var adjacencies = new Array();
  89672. var faceNormals = new Array();
  89673. var index;
  89674. var faceAdjacencies;
  89675. // Prepare faces
  89676. for (index = 0; index < indices.length; index += 3) {
  89677. faceAdjacencies = new FaceAdjacencies();
  89678. var p0Index = indices[index];
  89679. var p1Index = indices[index + 1];
  89680. var p2Index = indices[index + 2];
  89681. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  89682. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  89683. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  89684. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  89685. faceNormal.normalize();
  89686. faceNormals.push(faceNormal);
  89687. adjacencies.push(faceAdjacencies);
  89688. }
  89689. // Scan
  89690. for (index = 0; index < adjacencies.length; index++) {
  89691. faceAdjacencies = adjacencies[index];
  89692. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  89693. var otherFaceAdjacencies = adjacencies[otherIndex];
  89694. if (faceAdjacencies.edgesConnectedCount === 3) {
  89695. break;
  89696. }
  89697. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  89698. continue;
  89699. }
  89700. var otherP0 = indices[otherIndex * 3];
  89701. var otherP1 = indices[otherIndex * 3 + 1];
  89702. var otherP2 = indices[otherIndex * 3 + 2];
  89703. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  89704. var otherEdgeIndex = 0;
  89705. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  89706. continue;
  89707. }
  89708. switch (edgeIndex) {
  89709. case 0:
  89710. if (this._checkVerticesInsteadOfIndices) {
  89711. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89712. }
  89713. else {
  89714. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  89715. }
  89716. break;
  89717. case 1:
  89718. if (this._checkVerticesInsteadOfIndices) {
  89719. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89720. }
  89721. else {
  89722. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  89723. }
  89724. break;
  89725. case 2:
  89726. if (this._checkVerticesInsteadOfIndices) {
  89727. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89728. }
  89729. else {
  89730. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  89731. }
  89732. break;
  89733. }
  89734. if (otherEdgeIndex === -1) {
  89735. continue;
  89736. }
  89737. faceAdjacencies.edges[edgeIndex] = otherIndex;
  89738. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  89739. faceAdjacencies.edgesConnectedCount++;
  89740. otherFaceAdjacencies.edgesConnectedCount++;
  89741. if (faceAdjacencies.edgesConnectedCount === 3) {
  89742. break;
  89743. }
  89744. }
  89745. }
  89746. }
  89747. // Create lines
  89748. for (index = 0; index < adjacencies.length; index++) {
  89749. // 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
  89750. var current = adjacencies[index];
  89751. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  89752. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  89753. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  89754. }
  89755. // Merge into a single mesh
  89756. var engine = this._source.getScene().getEngine();
  89757. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  89758. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  89759. this._ib = engine.createIndexBuffer(this._linesIndices);
  89760. this._indicesCount = this._linesIndices.length;
  89761. };
  89762. EdgesRenderer.prototype.render = function () {
  89763. var scene = this._source.getScene();
  89764. if (!this._lineShader.isReady() || !scene.activeCamera) {
  89765. return;
  89766. }
  89767. var engine = scene.getEngine();
  89768. this._lineShader._preBind();
  89769. // VBOs
  89770. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  89771. scene.resetCachedMaterial();
  89772. this._lineShader.setColor4("color", this._source.edgesColor);
  89773. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  89774. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  89775. }
  89776. else {
  89777. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  89778. }
  89779. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  89780. this._lineShader.bind(this._source.getWorldMatrix());
  89781. // Draw order
  89782. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  89783. this._lineShader.unbind();
  89784. engine.setDepthWrite(true);
  89785. };
  89786. return EdgesRenderer;
  89787. }());
  89788. BABYLON.EdgesRenderer = EdgesRenderer;
  89789. })(BABYLON || (BABYLON = {}));
  89790. //# sourceMappingURL=babylon.edgesRenderer.js.map
  89791. "use strict";
  89792. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89793. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89794. s = arguments[i];
  89795. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89796. t[p] = s[p];
  89797. }
  89798. return t;
  89799. };
  89800. var BABYLON;
  89801. (function (BABYLON) {
  89802. /**
  89803. * The effect layer Helps adding post process effect blended with the main pass.
  89804. *
  89805. * This can be for instance use to generate glow or higlight effects on the scene.
  89806. *
  89807. * The effect layer class can not be used directly and is intented to inherited from to be
  89808. * customized per effects.
  89809. */
  89810. var EffectLayer = /** @class */ (function () {
  89811. /**
  89812. * Instantiates a new effect Layer and references it in the scene.
  89813. * @param name The name of the layer
  89814. * @param scene The scene to use the layer in
  89815. */
  89816. function EffectLayer(
  89817. /** The Friendly of the effect in the scene */
  89818. name, scene) {
  89819. this._vertexBuffers = {};
  89820. this._maxSize = 0;
  89821. this._mainTextureDesiredSize = { width: 0, height: 0 };
  89822. this._shouldRender = true;
  89823. this._postProcesses = [];
  89824. this._textures = [];
  89825. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  89826. /**
  89827. * The clear color of the texture used to generate the glow map.
  89828. */
  89829. this.neutralColor = new BABYLON.Color4();
  89830. /**
  89831. * Specifies wether the highlight layer is enabled or not.
  89832. */
  89833. this.isEnabled = true;
  89834. /**
  89835. * An event triggered when the effect layer has been disposed.
  89836. */
  89837. this.onDisposeObservable = new BABYLON.Observable();
  89838. /**
  89839. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  89840. */
  89841. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  89842. /**
  89843. * An event triggered when the generated texture is being merged in the scene.
  89844. */
  89845. this.onBeforeComposeObservable = new BABYLON.Observable();
  89846. /**
  89847. * An event triggered when the generated texture has been merged in the scene.
  89848. */
  89849. this.onAfterComposeObservable = new BABYLON.Observable();
  89850. /**
  89851. * An event triggered when the efffect layer changes its size.
  89852. */
  89853. this.onSizeChangedObservable = new BABYLON.Observable();
  89854. this.name = name;
  89855. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89856. this._engine = scene.getEngine();
  89857. this._maxSize = this._engine.getCaps().maxTextureSize;
  89858. this._scene.effectLayers.push(this);
  89859. // Generate Buffers
  89860. this._generateIndexBuffer();
  89861. this._genrateVertexBuffer();
  89862. }
  89863. Object.defineProperty(EffectLayer.prototype, "camera", {
  89864. /**
  89865. * Gets the camera attached to the layer.
  89866. */
  89867. get: function () {
  89868. return this._effectLayerOptions.camera;
  89869. },
  89870. enumerable: true,
  89871. configurable: true
  89872. });
  89873. /**
  89874. * Initializes the effect layer with the required options.
  89875. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  89876. */
  89877. EffectLayer.prototype._init = function (options) {
  89878. // Adapt options
  89879. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89880. this._setMainTextureSize();
  89881. this._createMainTexture();
  89882. this._createTextureAndPostProcesses();
  89883. this._mergeEffect = this._createMergeEffect();
  89884. };
  89885. /**
  89886. * Generates the index buffer of the full screen quad blending to the main canvas.
  89887. */
  89888. EffectLayer.prototype._generateIndexBuffer = function () {
  89889. // Indices
  89890. var indices = [];
  89891. indices.push(0);
  89892. indices.push(1);
  89893. indices.push(2);
  89894. indices.push(0);
  89895. indices.push(2);
  89896. indices.push(3);
  89897. this._indexBuffer = this._engine.createIndexBuffer(indices);
  89898. };
  89899. /**
  89900. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  89901. */
  89902. EffectLayer.prototype._genrateVertexBuffer = function () {
  89903. // VBO
  89904. var vertices = [];
  89905. vertices.push(1, 1);
  89906. vertices.push(-1, 1);
  89907. vertices.push(-1, -1);
  89908. vertices.push(1, -1);
  89909. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89910. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89911. };
  89912. /**
  89913. * Sets the main texture desired size which is the closest power of two
  89914. * of the engine canvas size.
  89915. */
  89916. EffectLayer.prototype._setMainTextureSize = function () {
  89917. if (this._effectLayerOptions.mainTextureFixedSize) {
  89918. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  89919. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  89920. }
  89921. else {
  89922. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  89923. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  89924. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  89925. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  89926. }
  89927. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  89928. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  89929. };
  89930. /**
  89931. * Creates the main texture for the effect layer.
  89932. */
  89933. EffectLayer.prototype._createMainTexture = function () {
  89934. var _this = this;
  89935. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  89936. width: this._mainTextureDesiredSize.width,
  89937. height: this._mainTextureDesiredSize.height
  89938. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89939. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  89940. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89941. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89942. this._mainTexture.anisotropicFilteringLevel = 1;
  89943. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89944. this._mainTexture.renderParticles = false;
  89945. this._mainTexture.renderList = null;
  89946. this._mainTexture.ignoreCameraViewport = true;
  89947. // Custom render function
  89948. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89949. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  89950. var index;
  89951. var engine = _this._scene.getEngine();
  89952. if (depthOnlySubMeshes.length) {
  89953. engine.setColorWrite(false);
  89954. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89955. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  89956. }
  89957. engine.setColorWrite(true);
  89958. }
  89959. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89960. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  89961. }
  89962. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89963. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  89964. }
  89965. for (index = 0; index < transparentSubMeshes.length; index++) {
  89966. _this._renderSubMesh(transparentSubMeshes.data[index]);
  89967. }
  89968. };
  89969. this._mainTexture.onClearObservable.add(function (engine) {
  89970. engine.clear(_this.neutralColor, true, true, true);
  89971. });
  89972. };
  89973. /**
  89974. * Checks for the readiness of the element composing the layer.
  89975. * @param subMesh the mesh to check for
  89976. * @param useInstances specify wether or not to use instances to render the mesh
  89977. * @param emissiveTexture the associated emissive texture used to generate the glow
  89978. * @return true if ready otherwise, false
  89979. */
  89980. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  89981. var material = subMesh.getMaterial();
  89982. if (!material) {
  89983. return false;
  89984. }
  89985. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  89986. return false;
  89987. }
  89988. var defines = [];
  89989. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89990. var mesh = subMesh.getMesh();
  89991. var uv1 = false;
  89992. var uv2 = false;
  89993. // Alpha test
  89994. if (material && material.needAlphaTesting()) {
  89995. var alphaTexture = material.getAlphaTestTexture();
  89996. if (alphaTexture) {
  89997. defines.push("#define ALPHATEST");
  89998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89999. alphaTexture.coordinatesIndex === 1) {
  90000. defines.push("#define DIFFUSEUV2");
  90001. uv2 = true;
  90002. }
  90003. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90004. defines.push("#define DIFFUSEUV1");
  90005. uv1 = true;
  90006. }
  90007. }
  90008. }
  90009. // Emissive
  90010. if (emissiveTexture) {
  90011. defines.push("#define EMISSIVE");
  90012. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90013. emissiveTexture.coordinatesIndex === 1) {
  90014. defines.push("#define EMISSIVEUV2");
  90015. uv2 = true;
  90016. }
  90017. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90018. defines.push("#define EMISSIVEUV1");
  90019. uv1 = true;
  90020. }
  90021. }
  90022. if (uv1) {
  90023. attribs.push(BABYLON.VertexBuffer.UVKind);
  90024. defines.push("#define UV1");
  90025. }
  90026. if (uv2) {
  90027. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90028. defines.push("#define UV2");
  90029. }
  90030. // Bones
  90031. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90032. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90033. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90034. if (mesh.numBoneInfluencers > 4) {
  90035. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90036. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90037. }
  90038. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90039. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90040. }
  90041. else {
  90042. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90043. }
  90044. // Morph targets
  90045. var manager = mesh.morphTargetManager;
  90046. var morphInfluencers = 0;
  90047. if (manager) {
  90048. if (manager.numInfluencers > 0) {
  90049. defines.push("#define MORPHTARGETS");
  90050. morphInfluencers = manager.numInfluencers;
  90051. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  90052. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  90053. }
  90054. }
  90055. // Instances
  90056. if (useInstances) {
  90057. defines.push("#define INSTANCES");
  90058. attribs.push("world0");
  90059. attribs.push("world1");
  90060. attribs.push("world2");
  90061. attribs.push("world3");
  90062. }
  90063. // Get correct effect
  90064. var join = defines.join("\n");
  90065. if (this._cachedDefines !== join) {
  90066. this._cachedDefines = join;
  90067. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  90068. }
  90069. return this._effectLayerMapGenerationEffect.isReady();
  90070. };
  90071. /**
  90072. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  90073. */
  90074. EffectLayer.prototype.render = function () {
  90075. var currentEffect = this._mergeEffect;
  90076. // Check
  90077. if (!currentEffect.isReady())
  90078. return;
  90079. for (var i = 0; i < this._postProcesses.length; i++) {
  90080. if (!this._postProcesses[i].isReady()) {
  90081. return;
  90082. }
  90083. }
  90084. var engine = this._scene.getEngine();
  90085. this.onBeforeComposeObservable.notifyObservers(this);
  90086. // Render
  90087. engine.enableEffect(currentEffect);
  90088. engine.setState(false);
  90089. // VBOs
  90090. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  90091. // Cache
  90092. var previousAlphaMode = engine.getAlphaMode();
  90093. // Go Blend.
  90094. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  90095. // Blends the map on the main canvas.
  90096. this._internalRender(currentEffect);
  90097. // Restore Alpha
  90098. engine.setAlphaMode(previousAlphaMode);
  90099. this.onAfterComposeObservable.notifyObservers(this);
  90100. // Handle size changes.
  90101. var size = this._mainTexture.getSize();
  90102. this._setMainTextureSize();
  90103. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  90104. // Recreate RTT and post processes on size change.
  90105. this.onSizeChangedObservable.notifyObservers(this);
  90106. this._disposeTextureAndPostProcesses();
  90107. this._createMainTexture();
  90108. this._createTextureAndPostProcesses();
  90109. }
  90110. };
  90111. /**
  90112. * Determine if a given mesh will be used in the current effect.
  90113. * @param mesh mesh to test
  90114. * @returns true if the mesh will be used
  90115. */
  90116. EffectLayer.prototype.hasMesh = function (mesh) {
  90117. return true;
  90118. };
  90119. /**
  90120. * Returns true if the layer contains information to display, otherwise false.
  90121. * @returns true if the glow layer should be rendered
  90122. */
  90123. EffectLayer.prototype.shouldRender = function () {
  90124. return this.isEnabled && this._shouldRender;
  90125. };
  90126. /**
  90127. * Returns true if the mesh should render, otherwise false.
  90128. * @param mesh The mesh to render
  90129. * @returns true if it should render otherwise false
  90130. */
  90131. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  90132. return true;
  90133. };
  90134. /**
  90135. * Returns true if the mesh should render, otherwise false.
  90136. * @param mesh The mesh to render
  90137. * @returns true if it should render otherwise false
  90138. */
  90139. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  90140. return true;
  90141. };
  90142. /**
  90143. * Renders the submesh passed in parameter to the generation map.
  90144. */
  90145. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  90146. var _this = this;
  90147. if (!this.shouldRender()) {
  90148. return;
  90149. }
  90150. var material = subMesh.getMaterial();
  90151. var mesh = subMesh.getRenderingMesh();
  90152. var scene = this._scene;
  90153. var engine = scene.getEngine();
  90154. if (!material) {
  90155. return;
  90156. }
  90157. // Do not block in blend mode.
  90158. if (material.needAlphaBlendingForMesh(mesh)) {
  90159. return;
  90160. }
  90161. // Culling
  90162. engine.setState(material.backFaceCulling);
  90163. // Managing instances
  90164. var batch = mesh._getInstancesRenderList(subMesh._id);
  90165. if (batch.mustReturn) {
  90166. return;
  90167. }
  90168. // Early Exit per mesh
  90169. if (!this._shouldRenderMesh(mesh)) {
  90170. return;
  90171. }
  90172. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90173. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  90174. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  90175. engine.enableEffect(this._effectLayerMapGenerationEffect);
  90176. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  90177. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  90178. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  90179. // Alpha test
  90180. if (material && material.needAlphaTesting()) {
  90181. var alphaTexture = material.getAlphaTestTexture();
  90182. if (alphaTexture) {
  90183. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  90184. var textureMatrix = alphaTexture.getTextureMatrix();
  90185. if (textureMatrix) {
  90186. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  90187. }
  90188. }
  90189. }
  90190. // Glow emissive only
  90191. if (this._emissiveTextureAndColor.texture) {
  90192. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  90193. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  90194. }
  90195. // Bones
  90196. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90197. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90198. }
  90199. // Morph targets
  90200. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  90201. // Draw
  90202. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  90203. }
  90204. else {
  90205. // Need to reset refresh rate of the shadowMap
  90206. this._mainTexture.resetRefreshCounter();
  90207. }
  90208. };
  90209. /**
  90210. * Rebuild the required buffers.
  90211. * @ignore Internal use only.
  90212. */
  90213. EffectLayer.prototype._rebuild = function () {
  90214. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90215. if (vb) {
  90216. vb._rebuild();
  90217. }
  90218. this._generateIndexBuffer();
  90219. };
  90220. /**
  90221. * Dispose only the render target textures and post process.
  90222. */
  90223. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90224. this._mainTexture.dispose();
  90225. for (var i = 0; i < this._postProcesses.length; i++) {
  90226. if (this._postProcesses[i]) {
  90227. this._postProcesses[i].dispose();
  90228. }
  90229. }
  90230. this._postProcesses = [];
  90231. for (var i = 0; i < this._textures.length; i++) {
  90232. if (this._textures[i]) {
  90233. this._textures[i].dispose();
  90234. }
  90235. }
  90236. this._textures = [];
  90237. };
  90238. /**
  90239. * Dispose the highlight layer and free resources.
  90240. */
  90241. EffectLayer.prototype.dispose = function () {
  90242. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90243. if (vertexBuffer) {
  90244. vertexBuffer.dispose();
  90245. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90246. }
  90247. if (this._indexBuffer) {
  90248. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90249. this._indexBuffer = null;
  90250. }
  90251. // Clean textures and post processes
  90252. this._disposeTextureAndPostProcesses();
  90253. // Remove from scene
  90254. var index = this._scene.effectLayers.indexOf(this, 0);
  90255. if (index > -1) {
  90256. this._scene.effectLayers.splice(index, 1);
  90257. }
  90258. // Callback
  90259. this.onDisposeObservable.notifyObservers(this);
  90260. this.onDisposeObservable.clear();
  90261. this.onBeforeRenderMainTextureObservable.clear();
  90262. this.onBeforeComposeObservable.clear();
  90263. this.onAfterComposeObservable.clear();
  90264. this.onSizeChangedObservable.clear();
  90265. };
  90266. /**
  90267. * Gets the class name of the effect layer
  90268. * @returns the string with the class name of the effect layer
  90269. */
  90270. EffectLayer.prototype.getClassName = function () {
  90271. return "EffectLayer";
  90272. };
  90273. /**
  90274. * Creates an effect layer from parsed effect layer data
  90275. * @param parsedEffectLayer defines effect layer data
  90276. * @param scene defines the current scene
  90277. * @param rootUrl defines the root URL containing the effect layer information
  90278. * @returns a parsed effect Layer
  90279. */
  90280. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  90281. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  90282. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  90283. };
  90284. __decorate([
  90285. BABYLON.serialize()
  90286. ], EffectLayer.prototype, "name", void 0);
  90287. __decorate([
  90288. BABYLON.serializeAsColor4()
  90289. ], EffectLayer.prototype, "neutralColor", void 0);
  90290. __decorate([
  90291. BABYLON.serialize()
  90292. ], EffectLayer.prototype, "isEnabled", void 0);
  90293. __decorate([
  90294. BABYLON.serializeAsCameraReference()
  90295. ], EffectLayer.prototype, "camera", null);
  90296. return EffectLayer;
  90297. }());
  90298. BABYLON.EffectLayer = EffectLayer;
  90299. })(BABYLON || (BABYLON = {}));
  90300. //# sourceMappingURL=babylon.effectLayer.js.map
  90301. "use strict";
  90302. var BABYLON;
  90303. (function (BABYLON) {
  90304. /**
  90305. * Special Glow Blur post process only blurring the alpha channel
  90306. * It enforces keeping the most luminous color in the color channel.
  90307. */
  90308. var GlowBlurPostProcess = /** @class */ (function (_super) {
  90309. __extends(GlowBlurPostProcess, _super);
  90310. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  90311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90312. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  90313. _this.direction = direction;
  90314. _this.kernel = kernel;
  90315. _this.onApplyObservable.add(function (effect) {
  90316. effect.setFloat2("screenSize", _this.width, _this.height);
  90317. effect.setVector2("direction", _this.direction);
  90318. effect.setFloat("blurWidth", _this.kernel);
  90319. });
  90320. return _this;
  90321. }
  90322. return GlowBlurPostProcess;
  90323. }(BABYLON.PostProcess));
  90324. /**
  90325. * The highlight layer Helps adding a glow effect around a mesh.
  90326. *
  90327. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90328. * glowy meshes to your scene.
  90329. *
  90330. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  90331. */
  90332. var HighlightLayer = /** @class */ (function (_super) {
  90333. __extends(HighlightLayer, _super);
  90334. /**
  90335. * Instantiates a new highlight Layer and references it to the scene..
  90336. * @param name The name of the layer
  90337. * @param scene The scene to use the layer in
  90338. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  90339. */
  90340. function HighlightLayer(name, scene, options) {
  90341. var _this = _super.call(this, name, scene) || this;
  90342. _this.name = name;
  90343. /**
  90344. * Specifies whether or not the inner glow is ACTIVE in the layer.
  90345. */
  90346. _this.innerGlow = true;
  90347. /**
  90348. * Specifies whether or not the outer glow is ACTIVE in the layer.
  90349. */
  90350. _this.outerGlow = true;
  90351. /**
  90352. * An event triggered when the highlight layer is being blurred.
  90353. */
  90354. _this.onBeforeBlurObservable = new BABYLON.Observable();
  90355. /**
  90356. * An event triggered when the highlight layer has been blurred.
  90357. */
  90358. _this.onAfterBlurObservable = new BABYLON.Observable();
  90359. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  90360. _this._meshes = {};
  90361. _this._excludedMeshes = {};
  90362. _this.neutralColor = HighlightLayer.NeutralColor;
  90363. // Warn on stencil
  90364. if (!_this._engine.isStencilEnable) {
  90365. 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 }");
  90366. }
  90367. // Adapt options
  90368. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90369. // Initialize the layer
  90370. _this._init({
  90371. alphaBlendingMode: _this._options.alphaBlendingMode,
  90372. camera: _this._options.camera,
  90373. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90374. mainTextureRatio: _this._options.mainTextureRatio
  90375. });
  90376. // Do not render as long as no meshes have been added
  90377. _this._shouldRender = false;
  90378. return _this;
  90379. }
  90380. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  90381. /**
  90382. * Gets the horizontal size of the blur.
  90383. */
  90384. get: function () {
  90385. return this._horizontalBlurPostprocess.kernel;
  90386. },
  90387. /**
  90388. * Specifies the horizontal size of the blur.
  90389. */
  90390. set: function (value) {
  90391. this._horizontalBlurPostprocess.kernel = value;
  90392. },
  90393. enumerable: true,
  90394. configurable: true
  90395. });
  90396. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  90397. /**
  90398. * Gets the vertical size of the blur.
  90399. */
  90400. get: function () {
  90401. return this._verticalBlurPostprocess.kernel;
  90402. },
  90403. /**
  90404. * Specifies the vertical size of the blur.
  90405. */
  90406. set: function (value) {
  90407. this._verticalBlurPostprocess.kernel = value;
  90408. },
  90409. enumerable: true,
  90410. configurable: true
  90411. });
  90412. /**
  90413. * Get the effect name of the layer.
  90414. * @return The effect name
  90415. */
  90416. HighlightLayer.prototype.getEffectName = function () {
  90417. return HighlightLayer.EffectName;
  90418. };
  90419. /**
  90420. * Create the merge effect. This is the shader use to blit the information back
  90421. * to the main canvas at the end of the scene rendering.
  90422. */
  90423. HighlightLayer.prototype._createMergeEffect = function () {
  90424. // Effect
  90425. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  90426. };
  90427. /**
  90428. * Creates the render target textures and post processes used in the highlight layer.
  90429. */
  90430. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  90431. var _this = this;
  90432. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  90433. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  90434. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90435. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90436. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  90437. width: blurTextureWidth,
  90438. height: blurTextureHeight
  90439. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90440. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90441. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90442. this._blurTexture.anisotropicFilteringLevel = 16;
  90443. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90444. this._blurTexture.renderParticles = false;
  90445. this._blurTexture.ignoreCameraViewport = true;
  90446. this._textures = [this._blurTexture];
  90447. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  90448. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90449. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  90450. effect.setTexture("textureSampler", _this._mainTexture);
  90451. });
  90452. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90453. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90454. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90455. });
  90456. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90457. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  90458. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  90459. });
  90460. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90461. }
  90462. else {
  90463. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  90464. width: blurTextureWidth,
  90465. height: blurTextureHeight
  90466. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90467. this._horizontalBlurPostprocess.width = blurTextureWidth;
  90468. this._horizontalBlurPostprocess.height = blurTextureHeight;
  90469. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90470. effect.setTexture("textureSampler", _this._mainTexture);
  90471. });
  90472. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  90473. width: blurTextureWidth,
  90474. height: blurTextureHeight
  90475. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90476. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  90477. }
  90478. this._mainTexture.onAfterUnbindObservable.add(function () {
  90479. _this.onBeforeBlurObservable.notifyObservers(_this);
  90480. var internalTexture = _this._blurTexture.getInternalTexture();
  90481. if (internalTexture) {
  90482. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  90483. }
  90484. _this.onAfterBlurObservable.notifyObservers(_this);
  90485. });
  90486. // Prevent autoClear.
  90487. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90488. };
  90489. /**
  90490. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90491. */
  90492. HighlightLayer.prototype.needStencil = function () {
  90493. return true;
  90494. };
  90495. /**
  90496. * Checks for the readiness of the element composing the layer.
  90497. * @param subMesh the mesh to check for
  90498. * @param useInstances specify wether or not to use instances to render the mesh
  90499. * @param emissiveTexture the associated emissive texture used to generate the glow
  90500. * @return true if ready otherwise, false
  90501. */
  90502. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  90503. var material = subMesh.getMaterial();
  90504. var mesh = subMesh.getRenderingMesh();
  90505. if (!material || !mesh || !this._meshes) {
  90506. return false;
  90507. }
  90508. var emissiveTexture = null;
  90509. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90510. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90511. emissiveTexture = material.emissiveTexture;
  90512. }
  90513. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90514. };
  90515. /**
  90516. * Implementation specific of rendering the generating effect on the main canvas.
  90517. * @param effect The effect used to render through
  90518. */
  90519. HighlightLayer.prototype._internalRender = function (effect) {
  90520. // Texture
  90521. effect.setTexture("textureSampler", this._blurTexture);
  90522. // Cache
  90523. var engine = this._engine;
  90524. var previousStencilBuffer = engine.getStencilBuffer();
  90525. var previousStencilFunction = engine.getStencilFunction();
  90526. var previousStencilMask = engine.getStencilMask();
  90527. var previousStencilOperationPass = engine.getStencilOperationPass();
  90528. var previousStencilOperationFail = engine.getStencilOperationFail();
  90529. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  90530. var previousStencilReference = engine.getStencilFunctionReference();
  90531. // Stencil operations
  90532. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  90533. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  90534. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  90535. // Draw order
  90536. engine.setStencilMask(0x00);
  90537. engine.setStencilBuffer(true);
  90538. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  90539. // 2 passes inner outer
  90540. if (this.outerGlow) {
  90541. effect.setFloat("offset", 0);
  90542. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  90543. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90544. }
  90545. if (this.innerGlow) {
  90546. effect.setFloat("offset", 1);
  90547. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  90548. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90549. }
  90550. // Restore Cache
  90551. engine.setStencilFunction(previousStencilFunction);
  90552. engine.setStencilMask(previousStencilMask);
  90553. engine.setStencilBuffer(previousStencilBuffer);
  90554. engine.setStencilOperationPass(previousStencilOperationPass);
  90555. engine.setStencilOperationFail(previousStencilOperationFail);
  90556. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  90557. engine.setStencilFunctionReference(previousStencilReference);
  90558. };
  90559. /**
  90560. * Returns true if the layer contains information to display, otherwise false.
  90561. */
  90562. HighlightLayer.prototype.shouldRender = function () {
  90563. if (_super.prototype.shouldRender.call(this)) {
  90564. return this._meshes ? true : false;
  90565. }
  90566. return false;
  90567. };
  90568. /**
  90569. * Returns true if the mesh should render, otherwise false.
  90570. * @param mesh The mesh to render
  90571. * @returns true if it should render otherwise false
  90572. */
  90573. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  90574. // Excluded Mesh
  90575. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  90576. return false;
  90577. }
  90578. ;
  90579. return true;
  90580. };
  90581. /**
  90582. * Sets the required values for both the emissive texture and and the main color.
  90583. */
  90584. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90585. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  90586. if (highlightLayerMesh) {
  90587. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  90588. }
  90589. else {
  90590. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90591. }
  90592. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  90593. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90594. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  90595. }
  90596. else {
  90597. this._emissiveTextureAndColor.texture = null;
  90598. }
  90599. };
  90600. /**
  90601. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  90602. * @param mesh The mesh to exclude from the highlight layer
  90603. */
  90604. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  90605. if (!this._excludedMeshes) {
  90606. return;
  90607. }
  90608. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90609. if (!meshExcluded) {
  90610. this._excludedMeshes[mesh.uniqueId] = {
  90611. mesh: mesh,
  90612. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  90613. mesh.getEngine().setStencilBuffer(false);
  90614. }),
  90615. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  90616. mesh.getEngine().setStencilBuffer(true);
  90617. }),
  90618. };
  90619. }
  90620. };
  90621. /**
  90622. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  90623. * @param mesh The mesh to highlight
  90624. */
  90625. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  90626. if (!this._excludedMeshes) {
  90627. return;
  90628. }
  90629. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  90630. if (meshExcluded) {
  90631. if (meshExcluded.beforeRender) {
  90632. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  90633. }
  90634. if (meshExcluded.afterRender) {
  90635. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  90636. }
  90637. }
  90638. this._excludedMeshes[mesh.uniqueId] = null;
  90639. };
  90640. /**
  90641. * Determine if a given mesh will be highlighted by the current HighlightLayer
  90642. * @param mesh mesh to test
  90643. * @returns true if the mesh will be highlighted by the current HighlightLayer
  90644. */
  90645. HighlightLayer.prototype.hasMesh = function (mesh) {
  90646. if (!this._meshes) {
  90647. return false;
  90648. }
  90649. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  90650. };
  90651. /**
  90652. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  90653. * @param mesh The mesh to highlight
  90654. * @param color The color of the highlight
  90655. * @param glowEmissiveOnly Extract the glow from the emissive texture
  90656. */
  90657. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  90658. var _this = this;
  90659. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  90660. if (!this._meshes) {
  90661. return;
  90662. }
  90663. var meshHighlight = this._meshes[mesh.uniqueId];
  90664. if (meshHighlight) {
  90665. meshHighlight.color = color;
  90666. }
  90667. else {
  90668. this._meshes[mesh.uniqueId] = {
  90669. mesh: mesh,
  90670. color: color,
  90671. // Lambda required for capture due to Observable this context
  90672. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  90673. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  90674. _this._defaultStencilReference(mesh);
  90675. }
  90676. else {
  90677. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  90678. }
  90679. }),
  90680. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  90681. glowEmissiveOnly: glowEmissiveOnly
  90682. };
  90683. }
  90684. this._shouldRender = true;
  90685. };
  90686. /**
  90687. * Remove a mesh from the highlight layer in order to make it stop glowing.
  90688. * @param mesh The mesh to highlight
  90689. */
  90690. HighlightLayer.prototype.removeMesh = function (mesh) {
  90691. if (!this._meshes) {
  90692. return;
  90693. }
  90694. var meshHighlight = this._meshes[mesh.uniqueId];
  90695. if (meshHighlight) {
  90696. if (meshHighlight.observerHighlight) {
  90697. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90698. }
  90699. if (meshHighlight.observerDefault) {
  90700. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90701. }
  90702. delete this._meshes[mesh.uniqueId];
  90703. }
  90704. this._shouldRender = false;
  90705. for (var meshHighlightToCheck in this._meshes) {
  90706. if (this._meshes[meshHighlightToCheck]) {
  90707. this._shouldRender = true;
  90708. break;
  90709. }
  90710. }
  90711. };
  90712. /**
  90713. * Force the stencil to the normal expected value for none glowing parts
  90714. */
  90715. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  90716. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  90717. };
  90718. /**
  90719. * Free any resources and references associated to a mesh.
  90720. * Internal use
  90721. * @param mesh The mesh to free.
  90722. */
  90723. HighlightLayer.prototype._disposeMesh = function (mesh) {
  90724. this.removeMesh(mesh);
  90725. this.removeExcludedMesh(mesh);
  90726. };
  90727. /**
  90728. * Dispose the highlight layer and free resources.
  90729. */
  90730. HighlightLayer.prototype.dispose = function () {
  90731. if (this._meshes) {
  90732. // Clean mesh references
  90733. for (var id in this._meshes) {
  90734. var meshHighlight = this._meshes[id];
  90735. if (meshHighlight && meshHighlight.mesh) {
  90736. if (meshHighlight.observerHighlight) {
  90737. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90738. }
  90739. if (meshHighlight.observerDefault) {
  90740. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90741. }
  90742. }
  90743. }
  90744. this._meshes = null;
  90745. }
  90746. if (this._excludedMeshes) {
  90747. for (var id in this._excludedMeshes) {
  90748. var meshHighlight = this._excludedMeshes[id];
  90749. if (meshHighlight) {
  90750. if (meshHighlight.beforeRender) {
  90751. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  90752. }
  90753. if (meshHighlight.afterRender) {
  90754. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  90755. }
  90756. }
  90757. }
  90758. this._excludedMeshes = null;
  90759. }
  90760. _super.prototype.dispose.call(this);
  90761. };
  90762. /**
  90763. * Gets the class name of the effect layer
  90764. * @returns the string with the class name of the effect layer
  90765. */
  90766. HighlightLayer.prototype.getClassName = function () {
  90767. return "HighlightLayer";
  90768. };
  90769. /**
  90770. * Serializes this Highlight layer
  90771. * @returns a serialized Highlight layer object
  90772. */
  90773. HighlightLayer.prototype.serialize = function () {
  90774. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90775. serializationObject.customType = "BABYLON.HighlightLayer";
  90776. // Highlighted meshes
  90777. serializationObject.meshes = [];
  90778. if (this._meshes) {
  90779. for (var m in this._meshes) {
  90780. var mesh = this._meshes[m];
  90781. if (mesh) {
  90782. serializationObject.meshes.push({
  90783. glowEmissiveOnly: mesh.glowEmissiveOnly,
  90784. color: mesh.color.asArray(),
  90785. meshId: mesh.mesh.id
  90786. });
  90787. }
  90788. }
  90789. }
  90790. // Excluded meshes
  90791. serializationObject.excludedMeshes = [];
  90792. if (this._excludedMeshes) {
  90793. for (var e in this._excludedMeshes) {
  90794. var excludedMesh = this._excludedMeshes[e];
  90795. if (excludedMesh) {
  90796. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  90797. }
  90798. }
  90799. }
  90800. return serializationObject;
  90801. };
  90802. /**
  90803. * Creates a Highlight layer from parsed Highlight layer data
  90804. * @param parsedHightlightLayer defines the Highlight layer data
  90805. * @param scene defines the current scene
  90806. * @param rootUrl defines the root URL containing the Highlight layer information
  90807. * @returns a parsed Highlight layer
  90808. */
  90809. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  90810. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  90811. var index;
  90812. // Excluded meshes
  90813. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  90814. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  90815. if (mesh) {
  90816. hl.addExcludedMesh(mesh);
  90817. }
  90818. }
  90819. // Included meshes
  90820. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  90821. var highlightedMesh = parsedHightlightLayer.meshes[index];
  90822. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  90823. if (mesh) {
  90824. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  90825. }
  90826. }
  90827. return hl;
  90828. };
  90829. /**
  90830. * Effect Name of the highlight layer.
  90831. */
  90832. HighlightLayer.EffectName = "HighlightLayer";
  90833. /**
  90834. * The neutral color used during the preparation of the glow effect.
  90835. * This is black by default as the blend operation is a blend operation.
  90836. */
  90837. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  90838. /**
  90839. * Stencil value used for glowing meshes.
  90840. */
  90841. HighlightLayer.GlowingMeshStencilReference = 0x02;
  90842. /**
  90843. * Stencil value used for the other meshes in the scene.
  90844. */
  90845. HighlightLayer.NormalMeshStencilReference = 0x01;
  90846. __decorate([
  90847. BABYLON.serialize()
  90848. ], HighlightLayer.prototype, "innerGlow", void 0);
  90849. __decorate([
  90850. BABYLON.serialize()
  90851. ], HighlightLayer.prototype, "outerGlow", void 0);
  90852. __decorate([
  90853. BABYLON.serialize()
  90854. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  90855. __decorate([
  90856. BABYLON.serialize()
  90857. ], HighlightLayer.prototype, "blurVerticalSize", null);
  90858. __decorate([
  90859. BABYLON.serialize("options")
  90860. ], HighlightLayer.prototype, "_options", void 0);
  90861. return HighlightLayer;
  90862. }(BABYLON.EffectLayer));
  90863. BABYLON.HighlightLayer = HighlightLayer;
  90864. })(BABYLON || (BABYLON = {}));
  90865. //# sourceMappingURL=babylon.highlightLayer.js.map
  90866. "use strict";
  90867. var BABYLON;
  90868. (function (BABYLON) {
  90869. /**
  90870. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  90871. *
  90872. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90873. * glowy meshes to your scene.
  90874. *
  90875. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  90876. */
  90877. var GlowLayer = /** @class */ (function (_super) {
  90878. __extends(GlowLayer, _super);
  90879. /**
  90880. * Instantiates a new glow Layer and references it to the scene.
  90881. * @param name The name of the layer
  90882. * @param scene The scene to use the layer in
  90883. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  90884. */
  90885. function GlowLayer(name, scene, options) {
  90886. var _this = _super.call(this, name, scene) || this;
  90887. _this._intensity = 1.0;
  90888. _this._includedOnlyMeshes = [];
  90889. _this._excludedMeshes = [];
  90890. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  90891. // Adapt options
  90892. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  90893. // Initialize the layer
  90894. _this._init({
  90895. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  90896. camera: _this._options.camera,
  90897. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90898. mainTextureRatio: _this._options.mainTextureRatio
  90899. });
  90900. return _this;
  90901. }
  90902. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  90903. /**
  90904. * Gets the kernel size of the blur.
  90905. */
  90906. get: function () {
  90907. return this._horizontalBlurPostprocess1.kernel;
  90908. },
  90909. /**
  90910. * Sets the kernel size of the blur.
  90911. */
  90912. set: function (value) {
  90913. this._horizontalBlurPostprocess1.kernel = value;
  90914. this._verticalBlurPostprocess1.kernel = value;
  90915. this._horizontalBlurPostprocess2.kernel = value;
  90916. this._verticalBlurPostprocess2.kernel = value;
  90917. },
  90918. enumerable: true,
  90919. configurable: true
  90920. });
  90921. Object.defineProperty(GlowLayer.prototype, "intensity", {
  90922. /**
  90923. * Gets the glow intensity.
  90924. */
  90925. get: function () {
  90926. return this._intensity;
  90927. },
  90928. /**
  90929. * Sets the glow intensity.
  90930. */
  90931. set: function (value) {
  90932. this._intensity = value;
  90933. },
  90934. enumerable: true,
  90935. configurable: true
  90936. });
  90937. /**
  90938. * Get the effect name of the layer.
  90939. * @return The effect name
  90940. */
  90941. GlowLayer.prototype.getEffectName = function () {
  90942. return GlowLayer.EffectName;
  90943. };
  90944. /**
  90945. * Create the merge effect. This is the shader use to blit the information back
  90946. * to the main canvas at the end of the scene rendering.
  90947. */
  90948. GlowLayer.prototype._createMergeEffect = function () {
  90949. // Effect
  90950. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  90951. };
  90952. /**
  90953. * Creates the render target textures and post processes used in the glow layer.
  90954. */
  90955. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  90956. var _this = this;
  90957. var blurTextureWidth = this._mainTextureDesiredSize.width;
  90958. var blurTextureHeight = this._mainTextureDesiredSize.height;
  90959. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90960. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90961. var textureType = 0;
  90962. if (this._engine.getCaps().textureHalfFloatRender) {
  90963. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90964. }
  90965. else {
  90966. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90967. }
  90968. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  90969. width: blurTextureWidth,
  90970. height: blurTextureHeight
  90971. }, this._scene, false, true, textureType);
  90972. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90973. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90974. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90975. this._blurTexture1.renderParticles = false;
  90976. this._blurTexture1.ignoreCameraViewport = true;
  90977. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  90978. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  90979. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  90980. width: blurTextureWidth2,
  90981. height: blurTextureHeight2
  90982. }, this._scene, false, true, textureType);
  90983. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90984. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90985. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90986. this._blurTexture2.renderParticles = false;
  90987. this._blurTexture2.ignoreCameraViewport = true;
  90988. this._textures = [this._blurTexture1, this._blurTexture2];
  90989. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90990. width: blurTextureWidth,
  90991. height: blurTextureHeight
  90992. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90993. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  90994. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  90995. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  90996. effect.setTexture("textureSampler", _this._mainTexture);
  90997. });
  90998. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90999. width: blurTextureWidth,
  91000. height: blurTextureHeight
  91001. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91002. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91003. width: blurTextureWidth2,
  91004. height: blurTextureHeight2
  91005. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91006. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  91007. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  91008. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  91009. effect.setTexture("textureSampler", _this._blurTexture1);
  91010. });
  91011. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91012. width: blurTextureWidth2,
  91013. height: blurTextureHeight2
  91014. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91015. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91016. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  91017. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91018. this._mainTexture.samples = this._options.mainTextureSamples;
  91019. this._mainTexture.onAfterUnbindObservable.add(function () {
  91020. var internalTexture = _this._blurTexture1.getInternalTexture();
  91021. if (internalTexture) {
  91022. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  91023. internalTexture = _this._blurTexture2.getInternalTexture();
  91024. if (internalTexture) {
  91025. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  91026. }
  91027. }
  91028. });
  91029. // Prevent autoClear.
  91030. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91031. };
  91032. /**
  91033. * Checks for the readiness of the element composing the layer.
  91034. * @param subMesh the mesh to check for
  91035. * @param useInstances specify wether or not to use instances to render the mesh
  91036. * @param emissiveTexture the associated emissive texture used to generate the glow
  91037. * @return true if ready otherwise, false
  91038. */
  91039. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  91040. var material = subMesh.getMaterial();
  91041. var mesh = subMesh.getRenderingMesh();
  91042. if (!material || !mesh) {
  91043. return false;
  91044. }
  91045. var emissiveTexture = material.emissiveTexture;
  91046. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91047. };
  91048. /**
  91049. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91050. */
  91051. GlowLayer.prototype.needStencil = function () {
  91052. return false;
  91053. };
  91054. /**
  91055. * Implementation specific of rendering the generating effect on the main canvas.
  91056. * @param effect The effect used to render through
  91057. */
  91058. GlowLayer.prototype._internalRender = function (effect) {
  91059. // Texture
  91060. effect.setTexture("textureSampler", this._blurTexture1);
  91061. effect.setTexture("textureSampler2", this._blurTexture2);
  91062. effect.setFloat("offset", this._intensity);
  91063. // Cache
  91064. var engine = this._engine;
  91065. var previousStencilBuffer = engine.getStencilBuffer();
  91066. // Draw order
  91067. engine.setStencilBuffer(false);
  91068. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91069. // Draw order
  91070. engine.setStencilBuffer(previousStencilBuffer);
  91071. };
  91072. /**
  91073. * Sets the required values for both the emissive texture and and the main color.
  91074. */
  91075. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91076. var textureLevel = 1.0;
  91077. if (this.customEmissiveTextureSelector) {
  91078. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  91079. }
  91080. else {
  91081. if (material) {
  91082. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91083. if (this._emissiveTextureAndColor.texture) {
  91084. textureLevel = this._emissiveTextureAndColor.texture.level;
  91085. }
  91086. }
  91087. else {
  91088. this._emissiveTextureAndColor.texture = null;
  91089. }
  91090. }
  91091. if (this.customEmissiveColorSelector) {
  91092. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  91093. }
  91094. else {
  91095. if (material.emissiveColor) {
  91096. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  91097. }
  91098. else {
  91099. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91100. }
  91101. }
  91102. };
  91103. /**
  91104. * Returns true if the mesh should render, otherwise false.
  91105. * @param mesh The mesh to render
  91106. * @returns true if it should render otherwise false
  91107. */
  91108. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  91109. return this.hasMesh(mesh);
  91110. };
  91111. /**
  91112. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  91113. * @param mesh The mesh to exclude from the glow layer
  91114. */
  91115. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  91116. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  91117. this._excludedMeshes.push(mesh.uniqueId);
  91118. }
  91119. };
  91120. /**
  91121. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  91122. * @param mesh The mesh to remove
  91123. */
  91124. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  91125. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  91126. if (index !== -1) {
  91127. this._excludedMeshes.splice(index, 1);
  91128. }
  91129. };
  91130. /**
  91131. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  91132. * @param mesh The mesh to include in the glow layer
  91133. */
  91134. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  91135. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  91136. this._includedOnlyMeshes.push(mesh.uniqueId);
  91137. }
  91138. };
  91139. /**
  91140. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  91141. * @param mesh The mesh to remove
  91142. */
  91143. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  91144. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  91145. if (index !== -1) {
  91146. this._includedOnlyMeshes.splice(index, 1);
  91147. }
  91148. };
  91149. /**
  91150. * Determine if a given mesh will be used in the glow layer
  91151. * @param mesh The mesh to test
  91152. * @returns true if the mesh will be highlighted by the current glow layer
  91153. */
  91154. GlowLayer.prototype.hasMesh = function (mesh) {
  91155. // Included Mesh
  91156. if (this._includedOnlyMeshes.length) {
  91157. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  91158. }
  91159. ;
  91160. // Excluded Mesh
  91161. if (this._excludedMeshes.length) {
  91162. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  91163. }
  91164. ;
  91165. return true;
  91166. };
  91167. /**
  91168. * Free any resources and references associated to a mesh.
  91169. * Internal use
  91170. * @param mesh The mesh to free.
  91171. */
  91172. GlowLayer.prototype._disposeMesh = function (mesh) {
  91173. this.removeIncludedOnlyMesh(mesh);
  91174. this.removeExcludedMesh(mesh);
  91175. };
  91176. /**
  91177. * Gets the class name of the effect layer
  91178. * @returns the string with the class name of the effect layer
  91179. */
  91180. GlowLayer.prototype.getClassName = function () {
  91181. return "GlowLayer";
  91182. };
  91183. /**
  91184. * Serializes this glow layer
  91185. * @returns a serialized glow layer object
  91186. */
  91187. GlowLayer.prototype.serialize = function () {
  91188. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91189. serializationObject.customType = "BABYLON.GlowLayer";
  91190. var index;
  91191. // Included meshes
  91192. serializationObject.includedMeshes = [];
  91193. if (this._includedOnlyMeshes.length) {
  91194. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  91195. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  91196. if (mesh) {
  91197. serializationObject.includedMeshes.push(mesh.id);
  91198. }
  91199. }
  91200. }
  91201. // Excluded meshes
  91202. serializationObject.excludedMeshes = [];
  91203. if (this._excludedMeshes.length) {
  91204. for (index = 0; index < this._excludedMeshes.length; index++) {
  91205. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91206. if (mesh) {
  91207. serializationObject.excludedMeshes.push(mesh.id);
  91208. }
  91209. }
  91210. }
  91211. return serializationObject;
  91212. };
  91213. /**
  91214. * Creates a Glow Layer from parsed glow layer data
  91215. * @param parsedGlowLayer defines glow layer data
  91216. * @param scene defines the current scene
  91217. * @param rootUrl defines the root URL containing the glow layer information
  91218. * @returns a parsed Glow Layer
  91219. */
  91220. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91221. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91222. var index;
  91223. // Excluded meshes
  91224. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91225. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91226. if (mesh) {
  91227. gl.addExcludedMesh(mesh);
  91228. }
  91229. }
  91230. // Included meshes
  91231. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91232. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91233. if (mesh) {
  91234. gl.addIncludedOnlyMesh(mesh);
  91235. }
  91236. }
  91237. return gl;
  91238. };
  91239. /**
  91240. * Effect Name of the layer.
  91241. */
  91242. GlowLayer.EffectName = "GlowLayer";
  91243. /**
  91244. * The default blur kernel size used for the glow.
  91245. */
  91246. GlowLayer.DefaultBlurKernelSize = 32;
  91247. /**
  91248. * The default texture size ratio used for the glow.
  91249. */
  91250. GlowLayer.DefaultTextureRatio = 0.5;
  91251. __decorate([
  91252. BABYLON.serialize()
  91253. ], GlowLayer.prototype, "blurKernelSize", null);
  91254. __decorate([
  91255. BABYLON.serialize()
  91256. ], GlowLayer.prototype, "intensity", null);
  91257. __decorate([
  91258. BABYLON.serialize("options")
  91259. ], GlowLayer.prototype, "_options", void 0);
  91260. return GlowLayer;
  91261. }(BABYLON.EffectLayer));
  91262. BABYLON.GlowLayer = GlowLayer;
  91263. })(BABYLON || (BABYLON = {}));
  91264. //# sourceMappingURL=babylon.glowLayer.js.map
  91265. "use strict";
  91266. var BABYLON;
  91267. (function (BABYLON) {
  91268. /**
  91269. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  91270. */
  91271. var AssetTaskState;
  91272. (function (AssetTaskState) {
  91273. /**
  91274. * Initialization
  91275. */
  91276. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  91277. /**
  91278. * Running
  91279. */
  91280. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  91281. /**
  91282. * Done
  91283. */
  91284. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  91285. /**
  91286. * Error
  91287. */
  91288. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  91289. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  91290. /**
  91291. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  91292. */
  91293. var AbstractAssetTask = /** @class */ (function () {
  91294. /**
  91295. * Creates a new {BABYLON.AssetsManager}
  91296. * @param name defines the name of the task
  91297. */
  91298. function AbstractAssetTask(
  91299. /**
  91300. * Task name
  91301. */ name) {
  91302. this.name = name;
  91303. this._isCompleted = false;
  91304. this._taskState = AssetTaskState.INIT;
  91305. }
  91306. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  91307. /**
  91308. * Get if the task is completed
  91309. */
  91310. get: function () {
  91311. return this._isCompleted;
  91312. },
  91313. enumerable: true,
  91314. configurable: true
  91315. });
  91316. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  91317. /**
  91318. * Gets the current state of the task
  91319. */
  91320. get: function () {
  91321. return this._taskState;
  91322. },
  91323. enumerable: true,
  91324. configurable: true
  91325. });
  91326. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  91327. /**
  91328. * Gets the current error object (if task is in error)
  91329. */
  91330. get: function () {
  91331. return this._errorObject;
  91332. },
  91333. enumerable: true,
  91334. configurable: true
  91335. });
  91336. /**
  91337. * Internal only
  91338. * @ignore
  91339. */
  91340. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  91341. if (this._errorObject) {
  91342. return;
  91343. }
  91344. this._errorObject = {
  91345. message: message,
  91346. exception: exception
  91347. };
  91348. };
  91349. /**
  91350. * Execute the current task
  91351. * @param scene defines the scene where you want your assets to be loaded
  91352. * @param onSuccess is a callback called when the task is successfully executed
  91353. * @param onError is a callback called if an error occurs
  91354. */
  91355. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91356. var _this = this;
  91357. this._taskState = AssetTaskState.RUNNING;
  91358. this.runTask(scene, function () {
  91359. _this.onDoneCallback(onSuccess, onError);
  91360. }, function (msg, exception) {
  91361. _this.onErrorCallback(onError, msg, exception);
  91362. });
  91363. };
  91364. /**
  91365. * Execute the current task
  91366. * @param scene defines the scene where you want your assets to be loaded
  91367. * @param onSuccess is a callback called when the task is successfully executed
  91368. * @param onError is a callback called if an error occurs
  91369. */
  91370. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91371. throw new Error("runTask is not implemented");
  91372. };
  91373. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  91374. this._taskState = AssetTaskState.ERROR;
  91375. this._errorObject = {
  91376. message: message,
  91377. exception: exception
  91378. };
  91379. if (this.onError) {
  91380. this.onError(this, message, exception);
  91381. }
  91382. onError();
  91383. };
  91384. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  91385. try {
  91386. this._taskState = AssetTaskState.DONE;
  91387. this._isCompleted = true;
  91388. if (this.onSuccess) {
  91389. this.onSuccess(this);
  91390. }
  91391. onSuccess();
  91392. }
  91393. catch (e) {
  91394. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  91395. }
  91396. };
  91397. return AbstractAssetTask;
  91398. }());
  91399. BABYLON.AbstractAssetTask = AbstractAssetTask;
  91400. /**
  91401. * Class used to share progress information about assets loading
  91402. */
  91403. var AssetsProgressEvent = /** @class */ (function () {
  91404. /**
  91405. * Creates a {BABYLON.AssetsProgressEvent}
  91406. * @param remainingCount defines the number of remaining tasks to process
  91407. * @param totalCount defines the total number of tasks
  91408. * @param task defines the task that was just processed
  91409. */
  91410. function AssetsProgressEvent(remainingCount, totalCount, task) {
  91411. this.remainingCount = remainingCount;
  91412. this.totalCount = totalCount;
  91413. this.task = task;
  91414. }
  91415. return AssetsProgressEvent;
  91416. }());
  91417. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  91418. /**
  91419. * Define a task used by {BABYLON.AssetsManager} to load meshes
  91420. */
  91421. var MeshAssetTask = /** @class */ (function (_super) {
  91422. __extends(MeshAssetTask, _super);
  91423. /**
  91424. * Creates a new {BABYLON.MeshAssetTask}
  91425. * @param name defines the name of the task
  91426. * @param meshesNames defines the list of mesh's names you want to load
  91427. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  91428. * @param sceneFilename defines the filename of the scene to load from
  91429. */
  91430. function MeshAssetTask(
  91431. /**
  91432. * Defines the name of the task
  91433. */
  91434. name,
  91435. /**
  91436. * Defines the list of mesh's names you want to load
  91437. */
  91438. meshesNames,
  91439. /**
  91440. * Defines the root url to use as a base to load your meshes and associated resources
  91441. */
  91442. rootUrl,
  91443. /**
  91444. * Defines the filename of the scene to load from
  91445. */
  91446. sceneFilename) {
  91447. var _this = _super.call(this, name) || this;
  91448. _this.name = name;
  91449. _this.meshesNames = meshesNames;
  91450. _this.rootUrl = rootUrl;
  91451. _this.sceneFilename = sceneFilename;
  91452. return _this;
  91453. }
  91454. /**
  91455. * Execute the current task
  91456. * @param scene defines the scene where you want your assets to be loaded
  91457. * @param onSuccess is a callback called when the task is successfully executed
  91458. * @param onError is a callback called if an error occurs
  91459. */
  91460. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91461. var _this = this;
  91462. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  91463. _this.loadedMeshes = meshes;
  91464. _this.loadedParticleSystems = particleSystems;
  91465. _this.loadedSkeletons = skeletons;
  91466. onSuccess();
  91467. }, null, function (scene, message, exception) {
  91468. onError(message, exception);
  91469. });
  91470. };
  91471. return MeshAssetTask;
  91472. }(AbstractAssetTask));
  91473. BABYLON.MeshAssetTask = MeshAssetTask;
  91474. /**
  91475. * Define a task used by {BABYLON.AssetsManager} to load text content
  91476. */
  91477. var TextFileAssetTask = /** @class */ (function (_super) {
  91478. __extends(TextFileAssetTask, _super);
  91479. /**
  91480. * Creates a new TextFileAssetTask object
  91481. * @param name defines the name of the task
  91482. * @param url defines the location of the file to load
  91483. */
  91484. function TextFileAssetTask(
  91485. /**
  91486. * Defines the name of the task
  91487. */
  91488. name,
  91489. /**
  91490. * Defines the location of the file to load
  91491. */
  91492. url) {
  91493. var _this = _super.call(this, name) || this;
  91494. _this.name = name;
  91495. _this.url = url;
  91496. return _this;
  91497. }
  91498. /**
  91499. * Execute the current task
  91500. * @param scene defines the scene where you want your assets to be loaded
  91501. * @param onSuccess is a callback called when the task is successfully executed
  91502. * @param onError is a callback called if an error occurs
  91503. */
  91504. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91505. var _this = this;
  91506. scene._loadFile(this.url, function (data) {
  91507. _this.text = data;
  91508. onSuccess();
  91509. }, undefined, false, false, function (request, exception) {
  91510. if (request) {
  91511. onError(request.status + " " + request.statusText, exception);
  91512. }
  91513. });
  91514. };
  91515. return TextFileAssetTask;
  91516. }(AbstractAssetTask));
  91517. BABYLON.TextFileAssetTask = TextFileAssetTask;
  91518. /**
  91519. * Define a task used by {BABYLON.AssetsManager} to load binary data
  91520. */
  91521. var BinaryFileAssetTask = /** @class */ (function (_super) {
  91522. __extends(BinaryFileAssetTask, _super);
  91523. /**
  91524. * Creates a new BinaryFileAssetTask object
  91525. * @param name defines the name of the new task
  91526. * @param url defines the location of the file to load
  91527. */
  91528. function BinaryFileAssetTask(
  91529. /**
  91530. * Defines the name of the task
  91531. */
  91532. name,
  91533. /**
  91534. * Defines the location of the file to load
  91535. */
  91536. url) {
  91537. var _this = _super.call(this, name) || this;
  91538. _this.name = name;
  91539. _this.url = url;
  91540. return _this;
  91541. }
  91542. /**
  91543. * Execute the current task
  91544. * @param scene defines the scene where you want your assets to be loaded
  91545. * @param onSuccess is a callback called when the task is successfully executed
  91546. * @param onError is a callback called if an error occurs
  91547. */
  91548. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91549. var _this = this;
  91550. scene._loadFile(this.url, function (data) {
  91551. _this.data = data;
  91552. onSuccess();
  91553. }, undefined, true, true, function (request, exception) {
  91554. if (request) {
  91555. onError(request.status + " " + request.statusText, exception);
  91556. }
  91557. });
  91558. };
  91559. return BinaryFileAssetTask;
  91560. }(AbstractAssetTask));
  91561. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  91562. /**
  91563. * Define a task used by {BABYLON.AssetsManager} to load images
  91564. */
  91565. var ImageAssetTask = /** @class */ (function (_super) {
  91566. __extends(ImageAssetTask, _super);
  91567. /**
  91568. * Creates a new ImageAssetTask
  91569. * @param name defines the name of the task
  91570. * @param url defines the location of the image to load
  91571. */
  91572. function ImageAssetTask(
  91573. /**
  91574. * Defines the name of the task
  91575. */
  91576. name,
  91577. /**
  91578. * Defines the location of the image to load
  91579. */
  91580. url) {
  91581. var _this = _super.call(this, name) || this;
  91582. _this.name = name;
  91583. _this.url = url;
  91584. return _this;
  91585. }
  91586. /**
  91587. * Execute the current task
  91588. * @param scene defines the scene where you want your assets to be loaded
  91589. * @param onSuccess is a callback called when the task is successfully executed
  91590. * @param onError is a callback called if an error occurs
  91591. */
  91592. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91593. var _this = this;
  91594. var img = new Image();
  91595. BABYLON.Tools.SetCorsBehavior(this.url, img);
  91596. img.onload = function () {
  91597. _this.image = img;
  91598. onSuccess();
  91599. };
  91600. img.onerror = function (err) {
  91601. onError("Error loading image", err);
  91602. };
  91603. img.src = this.url;
  91604. };
  91605. return ImageAssetTask;
  91606. }(AbstractAssetTask));
  91607. BABYLON.ImageAssetTask = ImageAssetTask;
  91608. /**
  91609. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  91610. */
  91611. var TextureAssetTask = /** @class */ (function (_super) {
  91612. __extends(TextureAssetTask, _super);
  91613. /**
  91614. * Creates a new TextureAssetTask object
  91615. * @param name defines the name of the task
  91616. * @param url defines the location of the file to load
  91617. * @param noMipmap defines if mipmap should not be generated (default is false)
  91618. * @param invertY defines if texture must be inverted on Y axis (default is false)
  91619. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91620. */
  91621. function TextureAssetTask(
  91622. /**
  91623. * Defines the name of the task
  91624. */
  91625. name,
  91626. /**
  91627. * Defines the location of the file to load
  91628. */
  91629. url,
  91630. /**
  91631. * Defines if mipmap should not be generated (default is false)
  91632. */
  91633. noMipmap,
  91634. /**
  91635. * Defines if texture must be inverted on Y axis (default is false)
  91636. */
  91637. invertY,
  91638. /**
  91639. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  91640. */
  91641. samplingMode) {
  91642. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91643. var _this = _super.call(this, name) || this;
  91644. _this.name = name;
  91645. _this.url = url;
  91646. _this.noMipmap = noMipmap;
  91647. _this.invertY = invertY;
  91648. _this.samplingMode = samplingMode;
  91649. return _this;
  91650. }
  91651. /**
  91652. * Execute the current task
  91653. * @param scene defines the scene where you want your assets to be loaded
  91654. * @param onSuccess is a callback called when the task is successfully executed
  91655. * @param onError is a callback called if an error occurs
  91656. */
  91657. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91658. var onload = function () {
  91659. onSuccess();
  91660. };
  91661. var onerror = function (message, exception) {
  91662. onError(message, exception);
  91663. };
  91664. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  91665. };
  91666. return TextureAssetTask;
  91667. }(AbstractAssetTask));
  91668. BABYLON.TextureAssetTask = TextureAssetTask;
  91669. /**
  91670. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  91671. */
  91672. var CubeTextureAssetTask = /** @class */ (function (_super) {
  91673. __extends(CubeTextureAssetTask, _super);
  91674. /**
  91675. * Creates a new CubeTextureAssetTask
  91676. * @param name defines the name of the task
  91677. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91678. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91679. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91680. * @param files defines the explicit list of files (undefined by default)
  91681. */
  91682. function CubeTextureAssetTask(
  91683. /**
  91684. * Defines the name of the task
  91685. */
  91686. name,
  91687. /**
  91688. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91689. */
  91690. url,
  91691. /**
  91692. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91693. */
  91694. extensions,
  91695. /**
  91696. * Defines if mipmaps should not be generated (default is false)
  91697. */
  91698. noMipmap,
  91699. /**
  91700. * Defines the explicit list of files (undefined by default)
  91701. */
  91702. files) {
  91703. var _this = _super.call(this, name) || this;
  91704. _this.name = name;
  91705. _this.url = url;
  91706. _this.extensions = extensions;
  91707. _this.noMipmap = noMipmap;
  91708. _this.files = files;
  91709. return _this;
  91710. }
  91711. /**
  91712. * Execute the current task
  91713. * @param scene defines the scene where you want your assets to be loaded
  91714. * @param onSuccess is a callback called when the task is successfully executed
  91715. * @param onError is a callback called if an error occurs
  91716. */
  91717. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91718. var onload = function () {
  91719. onSuccess();
  91720. };
  91721. var onerror = function (message, exception) {
  91722. onError(message, exception);
  91723. };
  91724. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  91725. };
  91726. return CubeTextureAssetTask;
  91727. }(AbstractAssetTask));
  91728. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  91729. /**
  91730. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  91731. */
  91732. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  91733. __extends(HDRCubeTextureAssetTask, _super);
  91734. /**
  91735. * Creates a new HDRCubeTextureAssetTask object
  91736. * @param name defines the name of the task
  91737. * @param url defines the location of the file to load
  91738. * @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.
  91739. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91740. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91741. * @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)
  91742. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91743. */
  91744. function HDRCubeTextureAssetTask(
  91745. /**
  91746. * Defines the name of the task
  91747. */
  91748. name,
  91749. /**
  91750. * Defines the location of the file to load
  91751. */
  91752. url,
  91753. /**
  91754. * 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.
  91755. */
  91756. size,
  91757. /**
  91758. * Defines if mipmaps should not be generated (default is false)
  91759. */
  91760. noMipmap,
  91761. /**
  91762. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91763. */
  91764. generateHarmonics,
  91765. /**
  91766. * 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)
  91767. */
  91768. useInGammaSpace,
  91769. /**
  91770. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91771. */
  91772. usePMREMGenerator) {
  91773. if (noMipmap === void 0) { noMipmap = false; }
  91774. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91775. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91776. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91777. var _this = _super.call(this, name) || this;
  91778. _this.name = name;
  91779. _this.url = url;
  91780. _this.size = size;
  91781. _this.noMipmap = noMipmap;
  91782. _this.generateHarmonics = generateHarmonics;
  91783. _this.useInGammaSpace = useInGammaSpace;
  91784. _this.usePMREMGenerator = usePMREMGenerator;
  91785. return _this;
  91786. }
  91787. /**
  91788. * Execute the current task
  91789. * @param scene defines the scene where you want your assets to be loaded
  91790. * @param onSuccess is a callback called when the task is successfully executed
  91791. * @param onError is a callback called if an error occurs
  91792. */
  91793. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91794. var onload = function () {
  91795. onSuccess();
  91796. };
  91797. var onerror = function (message, exception) {
  91798. onError(message, exception);
  91799. };
  91800. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  91801. };
  91802. return HDRCubeTextureAssetTask;
  91803. }(AbstractAssetTask));
  91804. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  91805. /**
  91806. * This class can be used to easily import assets into a scene
  91807. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  91808. */
  91809. var AssetsManager = /** @class */ (function () {
  91810. /**
  91811. * Creates a new AssetsManager
  91812. * @param scene defines the scene to work on
  91813. */
  91814. function AssetsManager(scene) {
  91815. this._isLoading = false;
  91816. this._tasks = new Array();
  91817. this._waitingTasksCount = 0;
  91818. this._totalTasksCount = 0;
  91819. /**
  91820. * Observable called when all tasks are processed
  91821. */
  91822. this.onTaskSuccessObservable = new BABYLON.Observable();
  91823. /**
  91824. * Observable called when a task had an error
  91825. */
  91826. this.onTaskErrorObservable = new BABYLON.Observable();
  91827. /**
  91828. * Observable called when a task is successful
  91829. */
  91830. this.onTasksDoneObservable = new BABYLON.Observable();
  91831. /**
  91832. * Observable called when a task is done (whatever the result is)
  91833. */
  91834. this.onProgressObservable = new BABYLON.Observable();
  91835. /**
  91836. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  91837. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  91838. */
  91839. this.useDefaultLoadingScreen = true;
  91840. this._scene = scene;
  91841. }
  91842. /**
  91843. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  91844. * @param taskName defines the name of the new task
  91845. * @param meshesNames defines the name of meshes to load
  91846. * @param rootUrl defines the root url to use to locate files
  91847. * @param sceneFilename defines the filename of the scene file
  91848. * @returns a new {BABYLON.MeshAssetTask} object
  91849. */
  91850. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  91851. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  91852. this._tasks.push(task);
  91853. return task;
  91854. };
  91855. /**
  91856. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  91857. * @param taskName defines the name of the new task
  91858. * @param url defines the url of the file to load
  91859. * @returns a new {BABYLON.TextFileAssetTask} object
  91860. */
  91861. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  91862. var task = new TextFileAssetTask(taskName, url);
  91863. this._tasks.push(task);
  91864. return task;
  91865. };
  91866. /**
  91867. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  91868. * @param taskName defines the name of the new task
  91869. * @param url defines the url of the file to load
  91870. * @returns a new {BABYLON.BinaryFileAssetTask} object
  91871. */
  91872. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  91873. var task = new BinaryFileAssetTask(taskName, url);
  91874. this._tasks.push(task);
  91875. return task;
  91876. };
  91877. /**
  91878. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  91879. * @param taskName defines the name of the new task
  91880. * @param url defines the url of the file to load
  91881. * @returns a new {BABYLON.ImageAssetTask} object
  91882. */
  91883. AssetsManager.prototype.addImageTask = function (taskName, url) {
  91884. var task = new ImageAssetTask(taskName, url);
  91885. this._tasks.push(task);
  91886. return task;
  91887. };
  91888. /**
  91889. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  91890. * @param taskName defines the name of the new task
  91891. * @param url defines the url of the file to load
  91892. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91893. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  91894. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  91895. * @returns a new {BABYLON.TextureAssetTask} object
  91896. */
  91897. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  91898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91899. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  91900. this._tasks.push(task);
  91901. return task;
  91902. };
  91903. /**
  91904. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  91905. * @param taskName defines the name of the new task
  91906. * @param url defines the url of the file to load
  91907. * @param extensions defines the extension to use to load the cube map (can be null)
  91908. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91909. * @param files defines the list of files to load (can be null)
  91910. * @returns a new {BABYLON.CubeTextureAssetTask} object
  91911. */
  91912. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  91913. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  91914. this._tasks.push(task);
  91915. return task;
  91916. };
  91917. /**
  91918. *
  91919. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  91920. * @param taskName defines the name of the new task
  91921. * @param url defines the url of the file to load
  91922. * @param size defines the size you want for the cubemap (can be null)
  91923. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91924. * @param generateHarmonics defines if you want to automatically generate (true by default)
  91925. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  91926. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  91927. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  91928. */
  91929. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  91930. if (noMipmap === void 0) { noMipmap = false; }
  91931. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91932. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91933. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91934. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  91935. this._tasks.push(task);
  91936. return task;
  91937. };
  91938. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  91939. var _this = this;
  91940. this._waitingTasksCount--;
  91941. try {
  91942. if (task.taskState === AssetTaskState.DONE) {
  91943. // Let's remove successfull tasks
  91944. BABYLON.Tools.SetImmediate(function () {
  91945. var index = _this._tasks.indexOf(task);
  91946. if (index > -1) {
  91947. _this._tasks.splice(index, 1);
  91948. }
  91949. });
  91950. }
  91951. if (this.onProgress) {
  91952. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  91953. }
  91954. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  91955. }
  91956. catch (e) {
  91957. BABYLON.Tools.Error("Error running progress callbacks.");
  91958. console.log(e);
  91959. }
  91960. if (this._waitingTasksCount === 0) {
  91961. try {
  91962. if (this.onFinish) {
  91963. this.onFinish(this._tasks);
  91964. }
  91965. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91966. }
  91967. catch (e) {
  91968. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  91969. console.log(e);
  91970. }
  91971. this._isLoading = false;
  91972. this._scene.getEngine().hideLoadingUI();
  91973. }
  91974. };
  91975. AssetsManager.prototype._runTask = function (task) {
  91976. var _this = this;
  91977. var done = function () {
  91978. try {
  91979. if (_this.onTaskSuccess) {
  91980. _this.onTaskSuccess(task);
  91981. }
  91982. _this.onTaskSuccessObservable.notifyObservers(task);
  91983. _this._decreaseWaitingTasksCount(task);
  91984. }
  91985. catch (e) {
  91986. error("Error executing task success callbacks", e);
  91987. }
  91988. };
  91989. var error = function (message, exception) {
  91990. task._setErrorObject(message, exception);
  91991. if (_this.onTaskError) {
  91992. _this.onTaskError(task);
  91993. }
  91994. _this.onTaskErrorObservable.notifyObservers(task);
  91995. _this._decreaseWaitingTasksCount(task);
  91996. };
  91997. task.run(this._scene, done, error);
  91998. };
  91999. /**
  92000. * Reset the {BABYLON.AssetsManager} and remove all tasks
  92001. * @return the current instance of the {BABYLON.AssetsManager}
  92002. */
  92003. AssetsManager.prototype.reset = function () {
  92004. this._isLoading = false;
  92005. this._tasks = new Array();
  92006. return this;
  92007. };
  92008. /**
  92009. * Start the loading process
  92010. * @return the current instance of the {BABYLON.AssetsManager}
  92011. */
  92012. AssetsManager.prototype.load = function () {
  92013. if (this._isLoading) {
  92014. return this;
  92015. }
  92016. this._isLoading = true;
  92017. this._waitingTasksCount = this._tasks.length;
  92018. this._totalTasksCount = this._tasks.length;
  92019. if (this._waitingTasksCount === 0) {
  92020. this._isLoading = false;
  92021. if (this.onFinish) {
  92022. this.onFinish(this._tasks);
  92023. }
  92024. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92025. return this;
  92026. }
  92027. if (this.useDefaultLoadingScreen) {
  92028. this._scene.getEngine().displayLoadingUI();
  92029. }
  92030. for (var index = 0; index < this._tasks.length; index++) {
  92031. var task = this._tasks[index];
  92032. this._runTask(task);
  92033. }
  92034. return this;
  92035. };
  92036. return AssetsManager;
  92037. }());
  92038. BABYLON.AssetsManager = AssetsManager;
  92039. })(BABYLON || (BABYLON = {}));
  92040. //# sourceMappingURL=babylon.assetsManager.js.map
  92041. "use strict";
  92042. var BABYLON;
  92043. (function (BABYLON) {
  92044. var serializedGeometries = [];
  92045. var serializeGeometry = function (geometry, serializationGeometries) {
  92046. if (serializedGeometries[geometry.id]) {
  92047. return;
  92048. }
  92049. if (geometry.doNotSerialize) {
  92050. return;
  92051. }
  92052. if (geometry instanceof BABYLON.BoxGeometry) {
  92053. serializationGeometries.boxes.push(geometry.serialize());
  92054. }
  92055. else if (geometry instanceof BABYLON.SphereGeometry) {
  92056. serializationGeometries.spheres.push(geometry.serialize());
  92057. }
  92058. else if (geometry instanceof BABYLON.CylinderGeometry) {
  92059. serializationGeometries.cylinders.push(geometry.serialize());
  92060. }
  92061. else if (geometry instanceof BABYLON.TorusGeometry) {
  92062. serializationGeometries.toruses.push(geometry.serialize());
  92063. }
  92064. else if (geometry instanceof BABYLON.GroundGeometry) {
  92065. serializationGeometries.grounds.push(geometry.serialize());
  92066. }
  92067. else if (geometry instanceof BABYLON.Plane) {
  92068. serializationGeometries.planes.push(geometry.serialize());
  92069. }
  92070. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  92071. serializationGeometries.torusKnots.push(geometry.serialize());
  92072. }
  92073. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  92074. throw new Error("Unknown primitive type");
  92075. }
  92076. else {
  92077. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  92078. }
  92079. serializedGeometries[geometry.id] = true;
  92080. };
  92081. var serializeMesh = function (mesh, serializationScene) {
  92082. var serializationObject = {};
  92083. // Geometry
  92084. var geometry = mesh._geometry;
  92085. if (geometry) {
  92086. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  92087. // 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
  92088. serializeGeometry(geometry, serializationScene.geometries);
  92089. }
  92090. }
  92091. // Custom
  92092. if (mesh.serialize) {
  92093. mesh.serialize(serializationObject);
  92094. }
  92095. return serializationObject;
  92096. };
  92097. var finalizeSingleMesh = function (mesh, serializationObject) {
  92098. //only works if the mesh is already loaded
  92099. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92100. //serialize material
  92101. if (mesh.material) {
  92102. if (mesh.material instanceof BABYLON.StandardMaterial) {
  92103. serializationObject.materials = serializationObject.materials || [];
  92104. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92105. serializationObject.materials.push(mesh.material.serialize());
  92106. }
  92107. }
  92108. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  92109. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  92110. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92111. serializationObject.multiMaterials.push(mesh.material.serialize());
  92112. }
  92113. }
  92114. }
  92115. //serialize geometry
  92116. var geometry = mesh._geometry;
  92117. if (geometry) {
  92118. if (!serializationObject.geometries) {
  92119. serializationObject.geometries = {};
  92120. serializationObject.geometries.boxes = [];
  92121. serializationObject.geometries.spheres = [];
  92122. serializationObject.geometries.cylinders = [];
  92123. serializationObject.geometries.toruses = [];
  92124. serializationObject.geometries.grounds = [];
  92125. serializationObject.geometries.planes = [];
  92126. serializationObject.geometries.torusKnots = [];
  92127. serializationObject.geometries.vertexData = [];
  92128. }
  92129. serializeGeometry(geometry, serializationObject.geometries);
  92130. }
  92131. // Skeletons
  92132. if (mesh.skeleton) {
  92133. serializationObject.skeletons = serializationObject.skeletons || [];
  92134. serializationObject.skeletons.push(mesh.skeleton.serialize());
  92135. }
  92136. //serialize the actual mesh
  92137. serializationObject.meshes = serializationObject.meshes || [];
  92138. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92139. }
  92140. };
  92141. var SceneSerializer = /** @class */ (function () {
  92142. function SceneSerializer() {
  92143. }
  92144. SceneSerializer.ClearCache = function () {
  92145. serializedGeometries = [];
  92146. };
  92147. SceneSerializer.Serialize = function (scene) {
  92148. var serializationObject = {};
  92149. SceneSerializer.ClearCache();
  92150. // Scene
  92151. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  92152. serializationObject.autoClear = scene.autoClear;
  92153. serializationObject.clearColor = scene.clearColor.asArray();
  92154. serializationObject.ambientColor = scene.ambientColor.asArray();
  92155. serializationObject.gravity = scene.gravity.asArray();
  92156. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  92157. serializationObject.workerCollisions = scene.workerCollisions;
  92158. // Fog
  92159. if (scene.fogMode && scene.fogMode !== 0) {
  92160. serializationObject.fogMode = scene.fogMode;
  92161. serializationObject.fogColor = scene.fogColor.asArray();
  92162. serializationObject.fogStart = scene.fogStart;
  92163. serializationObject.fogEnd = scene.fogEnd;
  92164. serializationObject.fogDensity = scene.fogDensity;
  92165. }
  92166. //Physics
  92167. if (scene.isPhysicsEnabled()) {
  92168. var physicEngine = scene.getPhysicsEngine();
  92169. if (physicEngine) {
  92170. serializationObject.physicsEnabled = true;
  92171. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  92172. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  92173. }
  92174. }
  92175. // Metadata
  92176. if (scene.metadata) {
  92177. serializationObject.metadata = scene.metadata;
  92178. }
  92179. // Morph targets
  92180. serializationObject.morphTargetManagers = [];
  92181. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  92182. var abstractMesh = _a[_i];
  92183. var manager = abstractMesh.morphTargetManager;
  92184. if (manager) {
  92185. serializationObject.morphTargetManagers.push(manager.serialize());
  92186. }
  92187. }
  92188. // Lights
  92189. serializationObject.lights = [];
  92190. var index;
  92191. var light;
  92192. for (index = 0; index < scene.lights.length; index++) {
  92193. light = scene.lights[index];
  92194. if (!light.doNotSerialize) {
  92195. serializationObject.lights.push(light.serialize());
  92196. }
  92197. }
  92198. // Cameras
  92199. serializationObject.cameras = [];
  92200. for (index = 0; index < scene.cameras.length; index++) {
  92201. var camera = scene.cameras[index];
  92202. if (!camera.doNotSerialize) {
  92203. serializationObject.cameras.push(camera.serialize());
  92204. }
  92205. }
  92206. if (scene.activeCamera) {
  92207. serializationObject.activeCameraID = scene.activeCamera.id;
  92208. }
  92209. // Animations
  92210. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92211. // Materials
  92212. serializationObject.materials = [];
  92213. serializationObject.multiMaterials = [];
  92214. var material;
  92215. for (index = 0; index < scene.materials.length; index++) {
  92216. material = scene.materials[index];
  92217. if (!material.doNotSerialize) {
  92218. serializationObject.materials.push(material.serialize());
  92219. }
  92220. }
  92221. // MultiMaterials
  92222. serializationObject.multiMaterials = [];
  92223. for (index = 0; index < scene.multiMaterials.length; index++) {
  92224. var multiMaterial = scene.multiMaterials[index];
  92225. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92226. }
  92227. // Environment texture
  92228. if (scene.environmentTexture) {
  92229. serializationObject.environmentTexture = scene.environmentTexture.name;
  92230. }
  92231. // Skeletons
  92232. serializationObject.skeletons = [];
  92233. for (index = 0; index < scene.skeletons.length; index++) {
  92234. var skeleton = scene.skeletons[index];
  92235. if (!skeleton.doNotSerialize) {
  92236. serializationObject.skeletons.push(skeleton.serialize());
  92237. }
  92238. }
  92239. // Transform nodes
  92240. serializationObject.transformNodes = [];
  92241. for (index = 0; index < scene.transformNodes.length; index++) {
  92242. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92243. }
  92244. // Geometries
  92245. serializationObject.geometries = {};
  92246. serializationObject.geometries.boxes = [];
  92247. serializationObject.geometries.spheres = [];
  92248. serializationObject.geometries.cylinders = [];
  92249. serializationObject.geometries.toruses = [];
  92250. serializationObject.geometries.grounds = [];
  92251. serializationObject.geometries.planes = [];
  92252. serializationObject.geometries.torusKnots = [];
  92253. serializationObject.geometries.vertexData = [];
  92254. serializedGeometries = [];
  92255. var geometries = scene.getGeometries();
  92256. for (index = 0; index < geometries.length; index++) {
  92257. var geometry = geometries[index];
  92258. if (geometry.isReady()) {
  92259. serializeGeometry(geometry, serializationObject.geometries);
  92260. }
  92261. }
  92262. // Meshes
  92263. serializationObject.meshes = [];
  92264. for (index = 0; index < scene.meshes.length; index++) {
  92265. var abstractMesh = scene.meshes[index];
  92266. if (abstractMesh instanceof BABYLON.Mesh) {
  92267. var mesh = abstractMesh;
  92268. if (!mesh.doNotSerialize) {
  92269. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92270. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92271. }
  92272. }
  92273. }
  92274. }
  92275. // Particles Systems
  92276. serializationObject.particleSystems = [];
  92277. for (index = 0; index < scene.particleSystems.length; index++) {
  92278. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  92279. }
  92280. // Lens flares
  92281. serializationObject.lensFlareSystems = [];
  92282. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  92283. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  92284. }
  92285. // Shadows
  92286. serializationObject.shadowGenerators = [];
  92287. for (index = 0; index < scene.lights.length; index++) {
  92288. light = scene.lights[index];
  92289. var shadowGenerator = light.getShadowGenerator();
  92290. if (shadowGenerator) {
  92291. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  92292. }
  92293. }
  92294. // Action Manager
  92295. if (scene.actionManager) {
  92296. serializationObject.actions = scene.actionManager.serialize("scene");
  92297. }
  92298. // Audio
  92299. serializationObject.sounds = [];
  92300. for (index = 0; index < scene.soundTracks.length; index++) {
  92301. var soundtrack = scene.soundTracks[index];
  92302. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  92303. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  92304. }
  92305. }
  92306. // Effect layers
  92307. serializationObject.effectLayers = [];
  92308. for (index = 0; index < scene.effectLayers.length; index++) {
  92309. var layer = scene.effectLayers[index];
  92310. if (layer.serialize) {
  92311. serializationObject.effectLayers.push(layer.serialize());
  92312. }
  92313. }
  92314. return serializationObject;
  92315. };
  92316. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  92317. if (withParents === void 0) { withParents = false; }
  92318. if (withChildren === void 0) { withChildren = false; }
  92319. var serializationObject = {};
  92320. SceneSerializer.ClearCache();
  92321. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  92322. if (withParents || withChildren) {
  92323. //deliberate for loop! not for each, appended should be processed as well.
  92324. for (var i = 0; i < toSerialize.length; ++i) {
  92325. if (withChildren) {
  92326. toSerialize[i].getDescendants().forEach(function (node) {
  92327. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  92328. toSerialize.push(node);
  92329. }
  92330. });
  92331. }
  92332. //make sure the array doesn't contain the object already
  92333. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  92334. toSerialize.push(toSerialize[i].parent);
  92335. }
  92336. }
  92337. }
  92338. toSerialize.forEach(function (mesh) {
  92339. finalizeSingleMesh(mesh, serializationObject);
  92340. });
  92341. return serializationObject;
  92342. };
  92343. return SceneSerializer;
  92344. }());
  92345. BABYLON.SceneSerializer = SceneSerializer;
  92346. })(BABYLON || (BABYLON = {}));
  92347. //# sourceMappingURL=babylon.sceneSerializer.js.map
  92348. "use strict";
  92349. var BABYLON;
  92350. (function (BABYLON) {
  92351. var ReflectionProbe = /** @class */ (function () {
  92352. function ReflectionProbe(name, size, scene, generateMipMaps) {
  92353. if (generateMipMaps === void 0) { generateMipMaps = true; }
  92354. var _this = this;
  92355. this.name = name;
  92356. this._viewMatrix = BABYLON.Matrix.Identity();
  92357. this._target = BABYLON.Vector3.Zero();
  92358. this._add = BABYLON.Vector3.Zero();
  92359. this._invertYAxis = false;
  92360. this.position = BABYLON.Vector3.Zero();
  92361. this._scene = scene;
  92362. this._scene.reflectionProbes.push(this);
  92363. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  92364. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  92365. switch (faceIndex) {
  92366. case 0:
  92367. _this._add.copyFromFloats(1, 0, 0);
  92368. break;
  92369. case 1:
  92370. _this._add.copyFromFloats(-1, 0, 0);
  92371. break;
  92372. case 2:
  92373. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  92374. break;
  92375. case 3:
  92376. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  92377. break;
  92378. case 4:
  92379. _this._add.copyFromFloats(0, 0, 1);
  92380. break;
  92381. case 5:
  92382. _this._add.copyFromFloats(0, 0, -1);
  92383. break;
  92384. }
  92385. if (_this._attachedMesh) {
  92386. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  92387. }
  92388. _this.position.addToRef(_this._add, _this._target);
  92389. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  92390. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  92391. scene._forcedViewPosition = _this.position;
  92392. });
  92393. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  92394. scene._forcedViewPosition = null;
  92395. scene.updateTransformMatrix(true);
  92396. });
  92397. if (scene.activeCamera) {
  92398. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  92399. }
  92400. }
  92401. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  92402. get: function () {
  92403. return this._renderTargetTexture.samples;
  92404. },
  92405. set: function (value) {
  92406. this._renderTargetTexture.samples = value;
  92407. },
  92408. enumerable: true,
  92409. configurable: true
  92410. });
  92411. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  92412. get: function () {
  92413. return this._renderTargetTexture.refreshRate;
  92414. },
  92415. set: function (value) {
  92416. this._renderTargetTexture.refreshRate = value;
  92417. },
  92418. enumerable: true,
  92419. configurable: true
  92420. });
  92421. ReflectionProbe.prototype.getScene = function () {
  92422. return this._scene;
  92423. };
  92424. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  92425. get: function () {
  92426. return this._renderTargetTexture;
  92427. },
  92428. enumerable: true,
  92429. configurable: true
  92430. });
  92431. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  92432. get: function () {
  92433. return this._renderTargetTexture.renderList;
  92434. },
  92435. enumerable: true,
  92436. configurable: true
  92437. });
  92438. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  92439. this._attachedMesh = mesh;
  92440. };
  92441. /**
  92442. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  92443. *
  92444. * @param renderingGroupId The rendering group id corresponding to its index
  92445. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  92446. */
  92447. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  92448. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  92449. };
  92450. ReflectionProbe.prototype.dispose = function () {
  92451. var index = this._scene.reflectionProbes.indexOf(this);
  92452. if (index !== -1) {
  92453. // Remove from the scene if found
  92454. this._scene.reflectionProbes.splice(index, 1);
  92455. }
  92456. if (this._renderTargetTexture) {
  92457. this._renderTargetTexture.dispose();
  92458. this._renderTargetTexture = null;
  92459. }
  92460. };
  92461. return ReflectionProbe;
  92462. }());
  92463. BABYLON.ReflectionProbe = ReflectionProbe;
  92464. })(BABYLON || (BABYLON = {}));
  92465. //# sourceMappingURL=babylon.reflectionProbe.js.map
  92466. "use strict";
  92467. var BABYLON;
  92468. (function (BABYLON) {
  92469. var Layer = /** @class */ (function () {
  92470. function Layer(name, imgUrl, scene, isBackground, color) {
  92471. this.name = name;
  92472. this.scale = new BABYLON.Vector2(1, 1);
  92473. this.offset = new BABYLON.Vector2(0, 0);
  92474. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  92475. this.layerMask = 0x0FFFFFFF;
  92476. this._vertexBuffers = {};
  92477. // Events
  92478. /**
  92479. * An event triggered when the layer is disposed.
  92480. */
  92481. this.onDisposeObservable = new BABYLON.Observable();
  92482. /**
  92483. * An event triggered before rendering the scene
  92484. */
  92485. this.onBeforeRenderObservable = new BABYLON.Observable();
  92486. /**
  92487. * An event triggered after rendering the scene
  92488. */
  92489. this.onAfterRenderObservable = new BABYLON.Observable();
  92490. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  92491. this.isBackground = isBackground === undefined ? true : isBackground;
  92492. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  92493. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  92494. this._scene.layers.push(this);
  92495. var engine = this._scene.getEngine();
  92496. // VBO
  92497. var vertices = [];
  92498. vertices.push(1, 1);
  92499. vertices.push(-1, 1);
  92500. vertices.push(-1, -1);
  92501. vertices.push(1, -1);
  92502. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92503. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92504. this._createIndexBuffer();
  92505. // Effects
  92506. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  92507. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  92508. }
  92509. Object.defineProperty(Layer.prototype, "onDispose", {
  92510. set: function (callback) {
  92511. if (this._onDisposeObserver) {
  92512. this.onDisposeObservable.remove(this._onDisposeObserver);
  92513. }
  92514. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  92515. },
  92516. enumerable: true,
  92517. configurable: true
  92518. });
  92519. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  92520. set: function (callback) {
  92521. if (this._onBeforeRenderObserver) {
  92522. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  92523. }
  92524. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  92525. },
  92526. enumerable: true,
  92527. configurable: true
  92528. });
  92529. Object.defineProperty(Layer.prototype, "onAfterRender", {
  92530. set: function (callback) {
  92531. if (this._onAfterRenderObserver) {
  92532. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  92533. }
  92534. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  92535. },
  92536. enumerable: true,
  92537. configurable: true
  92538. });
  92539. Layer.prototype._createIndexBuffer = function () {
  92540. var engine = this._scene.getEngine();
  92541. // Indices
  92542. var indices = [];
  92543. indices.push(0);
  92544. indices.push(1);
  92545. indices.push(2);
  92546. indices.push(0);
  92547. indices.push(2);
  92548. indices.push(3);
  92549. this._indexBuffer = engine.createIndexBuffer(indices);
  92550. };
  92551. Layer.prototype._rebuild = function () {
  92552. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92553. if (vb) {
  92554. vb._rebuild();
  92555. }
  92556. this._createIndexBuffer();
  92557. };
  92558. Layer.prototype.render = function () {
  92559. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  92560. // Check
  92561. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  92562. return;
  92563. var engine = this._scene.getEngine();
  92564. this.onBeforeRenderObservable.notifyObservers(this);
  92565. // Render
  92566. engine.enableEffect(currentEffect);
  92567. engine.setState(false);
  92568. // Texture
  92569. currentEffect.setTexture("textureSampler", this.texture);
  92570. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  92571. // Color
  92572. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  92573. // Scale / offset
  92574. currentEffect.setVector2("offset", this.offset);
  92575. currentEffect.setVector2("scale", this.scale);
  92576. // VBOs
  92577. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92578. // Draw order
  92579. if (!this.alphaTest) {
  92580. engine.setAlphaMode(this.alphaBlendingMode);
  92581. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92582. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  92583. }
  92584. else {
  92585. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92586. }
  92587. this.onAfterRenderObservable.notifyObservers(this);
  92588. };
  92589. Layer.prototype.dispose = function () {
  92590. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92591. if (vertexBuffer) {
  92592. vertexBuffer.dispose();
  92593. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92594. }
  92595. if (this._indexBuffer) {
  92596. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92597. this._indexBuffer = null;
  92598. }
  92599. if (this.texture) {
  92600. this.texture.dispose();
  92601. this.texture = null;
  92602. }
  92603. // Remove from scene
  92604. var index = this._scene.layers.indexOf(this);
  92605. this._scene.layers.splice(index, 1);
  92606. // Callback
  92607. this.onDisposeObservable.notifyObservers(this);
  92608. this.onDisposeObservable.clear();
  92609. this.onAfterRenderObservable.clear();
  92610. this.onBeforeRenderObservable.clear();
  92611. };
  92612. return Layer;
  92613. }());
  92614. BABYLON.Layer = Layer;
  92615. })(BABYLON || (BABYLON = {}));
  92616. //# sourceMappingURL=babylon.layer.js.map
  92617. "use strict";
  92618. var BABYLON;
  92619. (function (BABYLON) {
  92620. var TextureTools = /** @class */ (function () {
  92621. function TextureTools() {
  92622. }
  92623. /**
  92624. * Uses the GPU to create a copy texture rescaled at a given size
  92625. * @param texture Texture to copy from
  92626. * @param width Desired width
  92627. * @param height Desired height
  92628. * @return Generated texture
  92629. */
  92630. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  92631. if (useBilinearMode === void 0) { useBilinearMode = true; }
  92632. var scene = texture.getScene();
  92633. var engine = scene.getEngine();
  92634. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  92635. rtt.wrapU = texture.wrapU;
  92636. rtt.wrapV = texture.wrapV;
  92637. rtt.uOffset = texture.uOffset;
  92638. rtt.vOffset = texture.vOffset;
  92639. rtt.uScale = texture.uScale;
  92640. rtt.vScale = texture.vScale;
  92641. rtt.uAng = texture.uAng;
  92642. rtt.vAng = texture.vAng;
  92643. rtt.wAng = texture.wAng;
  92644. rtt.coordinatesIndex = texture.coordinatesIndex;
  92645. rtt.level = texture.level;
  92646. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  92647. rtt._texture.isReady = false;
  92648. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92649. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92650. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92651. passPostProcess.getEffect().executeWhenCompiled(function () {
  92652. passPostProcess.onApply = function (effect) {
  92653. effect.setTexture("textureSampler", texture);
  92654. };
  92655. var internalTexture = rtt.getInternalTexture();
  92656. if (internalTexture) {
  92657. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  92658. engine.unBindFramebuffer(internalTexture);
  92659. rtt.disposeFramebufferObjects();
  92660. passPostProcess.dispose();
  92661. internalTexture.isReady = true;
  92662. }
  92663. });
  92664. return rtt;
  92665. };
  92666. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  92667. if (!scene._environmentBRDFTexture) {
  92668. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92669. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92670. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92671. scene._environmentBRDFTexture = texture;
  92672. }
  92673. return scene._environmentBRDFTexture;
  92674. };
  92675. 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=";
  92676. return TextureTools;
  92677. }());
  92678. BABYLON.TextureTools = TextureTools;
  92679. })(BABYLON || (BABYLON = {}));
  92680. //# sourceMappingURL=babylon.textureTools.js.map
  92681. "use strict";
  92682. var BABYLON;
  92683. (function (BABYLON) {
  92684. var FramingBehavior = /** @class */ (function () {
  92685. function FramingBehavior() {
  92686. this._mode = FramingBehavior.FitFrustumSidesMode;
  92687. this._radiusScale = 1.0;
  92688. this._positionScale = 0.5;
  92689. this._defaultElevation = 0.3;
  92690. this._elevationReturnTime = 1500;
  92691. this._elevationReturnWaitTime = 1000;
  92692. this._zoomStopsAnimation = false;
  92693. this._framingTime = 1500;
  92694. this._isPointerDown = false;
  92695. this._lastInteractionTime = -Infinity;
  92696. // Framing control
  92697. this._animatables = new Array();
  92698. this._betaIsAnimating = false;
  92699. }
  92700. Object.defineProperty(FramingBehavior.prototype, "name", {
  92701. get: function () {
  92702. return "Framing";
  92703. },
  92704. enumerable: true,
  92705. configurable: true
  92706. });
  92707. Object.defineProperty(FramingBehavior.prototype, "mode", {
  92708. /**
  92709. * Gets current mode used by the behavior.
  92710. */
  92711. get: function () {
  92712. return this._mode;
  92713. },
  92714. /**
  92715. * Sets the current mode used by the behavior
  92716. */
  92717. set: function (mode) {
  92718. this._mode = mode;
  92719. },
  92720. enumerable: true,
  92721. configurable: true
  92722. });
  92723. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  92724. /**
  92725. * Gets the scale applied to the radius
  92726. */
  92727. get: function () {
  92728. return this._radiusScale;
  92729. },
  92730. /**
  92731. * Sets the scale applied to the radius (1 by default)
  92732. */
  92733. set: function (radius) {
  92734. this._radiusScale = radius;
  92735. },
  92736. enumerable: true,
  92737. configurable: true
  92738. });
  92739. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  92740. /**
  92741. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92742. */
  92743. get: function () {
  92744. return this._positionScale;
  92745. },
  92746. /**
  92747. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92748. */
  92749. set: function (scale) {
  92750. this._positionScale = scale;
  92751. },
  92752. enumerable: true,
  92753. configurable: true
  92754. });
  92755. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  92756. /**
  92757. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92758. * behaviour is triggered, in radians.
  92759. */
  92760. get: function () {
  92761. return this._defaultElevation;
  92762. },
  92763. /**
  92764. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92765. * behaviour is triggered, in radians.
  92766. */
  92767. set: function (elevation) {
  92768. this._defaultElevation = elevation;
  92769. },
  92770. enumerable: true,
  92771. configurable: true
  92772. });
  92773. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  92774. /**
  92775. * Gets the time (in milliseconds) taken to return to the default beta position.
  92776. * Negative value indicates camera should not return to default.
  92777. */
  92778. get: function () {
  92779. return this._elevationReturnTime;
  92780. },
  92781. /**
  92782. * Sets the time (in milliseconds) taken to return to the default beta position.
  92783. * Negative value indicates camera should not return to default.
  92784. */
  92785. set: function (speed) {
  92786. this._elevationReturnTime = speed;
  92787. },
  92788. enumerable: true,
  92789. configurable: true
  92790. });
  92791. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  92792. /**
  92793. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92794. */
  92795. get: function () {
  92796. return this._elevationReturnWaitTime;
  92797. },
  92798. /**
  92799. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92800. */
  92801. set: function (time) {
  92802. this._elevationReturnWaitTime = time;
  92803. },
  92804. enumerable: true,
  92805. configurable: true
  92806. });
  92807. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  92808. /**
  92809. * Gets the flag that indicates if user zooming should stop animation.
  92810. */
  92811. get: function () {
  92812. return this._zoomStopsAnimation;
  92813. },
  92814. /**
  92815. * Sets the flag that indicates if user zooming should stop animation.
  92816. */
  92817. set: function (flag) {
  92818. this._zoomStopsAnimation = flag;
  92819. },
  92820. enumerable: true,
  92821. configurable: true
  92822. });
  92823. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  92824. /**
  92825. * Gets the transition time when framing the mesh, in milliseconds
  92826. */
  92827. get: function () {
  92828. return this._framingTime;
  92829. },
  92830. /**
  92831. * Sets the transition time when framing the mesh, in milliseconds
  92832. */
  92833. set: function (time) {
  92834. this._framingTime = time;
  92835. },
  92836. enumerable: true,
  92837. configurable: true
  92838. });
  92839. FramingBehavior.prototype.init = function () {
  92840. // Do notihng
  92841. };
  92842. FramingBehavior.prototype.attach = function (camera) {
  92843. var _this = this;
  92844. this._attachedCamera = camera;
  92845. var scene = this._attachedCamera.getScene();
  92846. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  92847. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92848. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92849. _this._isPointerDown = true;
  92850. return;
  92851. }
  92852. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92853. _this._isPointerDown = false;
  92854. }
  92855. });
  92856. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92857. if (mesh) {
  92858. _this.zoomOnMesh(mesh);
  92859. }
  92860. });
  92861. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92862. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92863. _this._applyUserInteraction();
  92864. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  92865. // back to the default position after a given timeout
  92866. _this._maintainCameraAboveGround();
  92867. });
  92868. };
  92869. FramingBehavior.prototype.detach = function () {
  92870. if (!this._attachedCamera) {
  92871. return;
  92872. }
  92873. var scene = this._attachedCamera.getScene();
  92874. if (this._onPrePointerObservableObserver) {
  92875. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92876. }
  92877. if (this._onAfterCheckInputsObserver) {
  92878. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92879. }
  92880. if (this._onMeshTargetChangedObserver) {
  92881. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92882. }
  92883. this._attachedCamera = null;
  92884. };
  92885. /**
  92886. * Targets the given mesh and updates zoom level accordingly.
  92887. * @param mesh The mesh to target.
  92888. * @param radius Optional. If a cached radius position already exists, overrides default.
  92889. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92890. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92891. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92892. */
  92893. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92894. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92895. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92896. mesh.computeWorldMatrix(true);
  92897. var boundingBox = mesh.getBoundingInfo().boundingBox;
  92898. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  92899. };
  92900. /**
  92901. * Targets the given mesh with its children and updates zoom level accordingly.
  92902. * @param mesh The mesh to target.
  92903. * @param radius Optional. If a cached radius position already exists, overrides default.
  92904. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92905. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92906. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92907. */
  92908. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92909. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92910. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92911. mesh.computeWorldMatrix(true);
  92912. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  92913. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  92914. };
  92915. /**
  92916. * Targets the given meshes with their children and updates zoom level accordingly.
  92917. * @param meshes The mesh to target.
  92918. * @param radius Optional. If a cached radius position already exists, overrides default.
  92919. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92920. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92921. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92922. */
  92923. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  92924. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92925. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92926. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  92927. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  92928. for (var i = 0; i < meshes.length; i++) {
  92929. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  92930. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  92931. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  92932. }
  92933. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  92934. };
  92935. /**
  92936. * Targets the given mesh and updates zoom level accordingly.
  92937. * @param mesh The mesh to target.
  92938. * @param radius Optional. If a cached radius position already exists, overrides default.
  92939. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92940. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92941. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92942. */
  92943. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  92944. var _this = this;
  92945. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92946. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92947. var zoomTarget;
  92948. if (!this._attachedCamera) {
  92949. return;
  92950. }
  92951. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  92952. var bottom = minimumWorld.y;
  92953. var top = maximumWorld.y;
  92954. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  92955. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  92956. if (focusOnOriginXZ) {
  92957. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  92958. }
  92959. else {
  92960. var centerWorld = minimumWorld.add(radiusWorld);
  92961. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  92962. }
  92963. if (!this._vectorTransition) {
  92964. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  92965. }
  92966. this._betaIsAnimating = true;
  92967. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  92968. if (animatable) {
  92969. this._animatables.push(animatable);
  92970. }
  92971. // sets the radius and lower radius bounds
  92972. // Small delta ensures camera is not always at lower zoom limit.
  92973. var radius = 0;
  92974. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  92975. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92976. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  92977. radius = position;
  92978. }
  92979. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92980. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92981. if (this._attachedCamera.lowerRadiusLimit === null) {
  92982. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  92983. }
  92984. }
  92985. // Set sensibilities
  92986. var extend = maximumWorld.subtract(minimumWorld).length();
  92987. this._attachedCamera.panningSensibility = 5000 / extend;
  92988. this._attachedCamera.wheelPrecision = 100 / radius;
  92989. // transition to new radius
  92990. if (!this._radiusTransition) {
  92991. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92992. }
  92993. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  92994. _this.stopAllAnimations();
  92995. if (onAnimationEnd) {
  92996. onAnimationEnd();
  92997. }
  92998. if (_this._attachedCamera) {
  92999. _this._attachedCamera.storeState();
  93000. }
  93001. });
  93002. if (animatable) {
  93003. this._animatables.push(animatable);
  93004. }
  93005. };
  93006. /**
  93007. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  93008. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  93009. * frustum width.
  93010. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  93011. * to fully enclose the mesh in the viewing frustum.
  93012. */
  93013. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  93014. var size = maximumWorld.subtract(minimumWorld);
  93015. var boxVectorGlobalDiagonal = size.length();
  93016. var frustumSlope = this._getFrustumSlope();
  93017. // Formula for setting distance
  93018. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  93019. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  93020. // Horizon distance
  93021. var radius = radiusWithoutFraming * this._radiusScale;
  93022. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  93023. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  93024. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  93025. var camera = this._attachedCamera;
  93026. if (!camera) {
  93027. return 0;
  93028. }
  93029. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93030. // Don't exceed the requested limit
  93031. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  93032. }
  93033. // Don't exceed the upper radius limit
  93034. if (camera.upperRadiusLimit) {
  93035. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  93036. }
  93037. return distance;
  93038. };
  93039. /**
  93040. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  93041. * is automatically returned to its default position (expected to be above ground plane).
  93042. */
  93043. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  93044. var _this = this;
  93045. if (this._elevationReturnTime < 0) {
  93046. return;
  93047. }
  93048. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  93049. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  93050. var limitBeta = Math.PI * 0.5;
  93051. // Bring the camera back up if below the ground plane
  93052. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  93053. this._betaIsAnimating = true;
  93054. //Transition to new position
  93055. this.stopAllAnimations();
  93056. if (!this._betaTransition) {
  93057. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93058. }
  93059. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  93060. _this._clearAnimationLocks();
  93061. _this.stopAllAnimations();
  93062. });
  93063. if (animatabe) {
  93064. this._animatables.push(animatabe);
  93065. }
  93066. }
  93067. };
  93068. /**
  93069. * Returns the frustum slope based on the canvas ratio and camera FOV
  93070. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  93071. */
  93072. FramingBehavior.prototype._getFrustumSlope = function () {
  93073. // Calculate the viewport ratio
  93074. // Aspect Ratio is Height/Width.
  93075. var camera = this._attachedCamera;
  93076. if (!camera) {
  93077. return BABYLON.Vector2.Zero();
  93078. }
  93079. var engine = camera.getScene().getEngine();
  93080. var aspectRatio = engine.getAspectRatio(camera);
  93081. // Camera FOV is the vertical field of view (top-bottom) in radians.
  93082. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  93083. var frustumSlopeY = Math.tan(camera.fov / 2);
  93084. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  93085. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  93086. // along the forward vector.
  93087. var frustumSlopeX = frustumSlopeY * aspectRatio;
  93088. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  93089. };
  93090. /**
  93091. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  93092. */
  93093. FramingBehavior.prototype._clearAnimationLocks = function () {
  93094. this._betaIsAnimating = false;
  93095. };
  93096. /**
  93097. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93098. */
  93099. FramingBehavior.prototype._applyUserInteraction = function () {
  93100. if (this.isUserIsMoving) {
  93101. this._lastInteractionTime = BABYLON.Tools.Now;
  93102. this.stopAllAnimations();
  93103. this._clearAnimationLocks();
  93104. }
  93105. };
  93106. /**
  93107. * Stops and removes all animations that have been applied to the camera
  93108. */
  93109. FramingBehavior.prototype.stopAllAnimations = function () {
  93110. if (this._attachedCamera) {
  93111. this._attachedCamera.animations = [];
  93112. }
  93113. while (this._animatables.length) {
  93114. if (this._animatables[0]) {
  93115. this._animatables[0].onAnimationEnd = null;
  93116. this._animatables[0].stop();
  93117. }
  93118. this._animatables.shift();
  93119. }
  93120. };
  93121. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  93122. /**
  93123. * Gets a value indicating if the user is moving the camera
  93124. */
  93125. get: function () {
  93126. if (!this._attachedCamera) {
  93127. return false;
  93128. }
  93129. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93130. this._attachedCamera.inertialBetaOffset !== 0 ||
  93131. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93132. this._attachedCamera.inertialPanningX !== 0 ||
  93133. this._attachedCamera.inertialPanningY !== 0 ||
  93134. this._isPointerDown;
  93135. },
  93136. enumerable: true,
  93137. configurable: true
  93138. });
  93139. /**
  93140. * The easing function used by animations
  93141. */
  93142. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  93143. /**
  93144. * The easing mode used by animations
  93145. */
  93146. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  93147. // Statics
  93148. /**
  93149. * The camera can move all the way towards the mesh.
  93150. */
  93151. FramingBehavior.IgnoreBoundsSizeMode = 0;
  93152. /**
  93153. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  93154. */
  93155. FramingBehavior.FitFrustumSidesMode = 1;
  93156. return FramingBehavior;
  93157. }());
  93158. BABYLON.FramingBehavior = FramingBehavior;
  93159. })(BABYLON || (BABYLON = {}));
  93160. //# sourceMappingURL=babylon.framingBehavior.js.map
  93161. "use strict";
  93162. var BABYLON;
  93163. (function (BABYLON) {
  93164. /**
  93165. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  93166. */
  93167. var BouncingBehavior = /** @class */ (function () {
  93168. function BouncingBehavior() {
  93169. /**
  93170. * The duration of the animation, in milliseconds
  93171. */
  93172. this.transitionDuration = 450;
  93173. /**
  93174. * Length of the distance animated by the transition when lower radius is reached
  93175. */
  93176. this.lowerRadiusTransitionRange = 2;
  93177. /**
  93178. * Length of the distance animated by the transition when upper radius is reached
  93179. */
  93180. this.upperRadiusTransitionRange = -2;
  93181. this._autoTransitionRange = false;
  93182. // Animations
  93183. this._radiusIsAnimating = false;
  93184. this._radiusBounceTransition = null;
  93185. this._animatables = new Array();
  93186. }
  93187. Object.defineProperty(BouncingBehavior.prototype, "name", {
  93188. get: function () {
  93189. return "Bouncing";
  93190. },
  93191. enumerable: true,
  93192. configurable: true
  93193. });
  93194. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  93195. /**
  93196. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93197. */
  93198. get: function () {
  93199. return this._autoTransitionRange;
  93200. },
  93201. /**
  93202. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93203. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93204. */
  93205. set: function (value) {
  93206. var _this = this;
  93207. if (this._autoTransitionRange === value) {
  93208. return;
  93209. }
  93210. this._autoTransitionRange = value;
  93211. var camera = this._attachedCamera;
  93212. if (!camera) {
  93213. return;
  93214. }
  93215. if (value) {
  93216. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93217. if (!mesh) {
  93218. return;
  93219. }
  93220. mesh.computeWorldMatrix(true);
  93221. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93222. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93223. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93224. });
  93225. }
  93226. else if (this._onMeshTargetChangedObserver) {
  93227. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93228. }
  93229. },
  93230. enumerable: true,
  93231. configurable: true
  93232. });
  93233. BouncingBehavior.prototype.init = function () {
  93234. // Do notihng
  93235. };
  93236. BouncingBehavior.prototype.attach = function (camera) {
  93237. var _this = this;
  93238. this._attachedCamera = camera;
  93239. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93240. if (!_this._attachedCamera) {
  93241. return;
  93242. }
  93243. // Add the bounce animation to the lower radius limit
  93244. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93245. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93246. }
  93247. // Add the bounce animation to the upper radius limit
  93248. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93249. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93250. }
  93251. });
  93252. };
  93253. BouncingBehavior.prototype.detach = function () {
  93254. if (!this._attachedCamera) {
  93255. return;
  93256. }
  93257. if (this._onAfterCheckInputsObserver) {
  93258. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93259. }
  93260. if (this._onMeshTargetChangedObserver) {
  93261. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93262. }
  93263. this._attachedCamera = null;
  93264. };
  93265. /**
  93266. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93267. * @param radiusLimit The limit to check against.
  93268. * @return Bool to indicate if at limit.
  93269. */
  93270. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  93271. if (!this._attachedCamera) {
  93272. return false;
  93273. }
  93274. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  93275. return true;
  93276. }
  93277. return false;
  93278. };
  93279. /**
  93280. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  93281. * @param radiusDelta The delta by which to animate to. Can be negative.
  93282. */
  93283. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  93284. var _this = this;
  93285. if (!this._attachedCamera) {
  93286. return;
  93287. }
  93288. if (!this._radiusBounceTransition) {
  93289. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  93290. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  93291. }
  93292. // Prevent zoom until bounce has completed
  93293. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  93294. this._attachedCamera.wheelPrecision = Infinity;
  93295. this._attachedCamera.inertialRadiusOffset = 0;
  93296. // Animate to the radius limit
  93297. this.stopAllAnimations();
  93298. this._radiusIsAnimating = true;
  93299. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  93300. if (animatable) {
  93301. this._animatables.push(animatable);
  93302. }
  93303. };
  93304. /**
  93305. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  93306. */
  93307. BouncingBehavior.prototype._clearAnimationLocks = function () {
  93308. this._radiusIsAnimating = false;
  93309. if (this._attachedCamera) {
  93310. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  93311. }
  93312. };
  93313. /**
  93314. * Stops and removes all animations that have been applied to the camera
  93315. */
  93316. BouncingBehavior.prototype.stopAllAnimations = function () {
  93317. if (this._attachedCamera) {
  93318. this._attachedCamera.animations = [];
  93319. }
  93320. while (this._animatables.length) {
  93321. this._animatables[0].onAnimationEnd = null;
  93322. this._animatables[0].stop();
  93323. this._animatables.shift();
  93324. }
  93325. };
  93326. /**
  93327. * The easing function used by animations
  93328. */
  93329. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  93330. /**
  93331. * The easing mode used by animations
  93332. */
  93333. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  93334. return BouncingBehavior;
  93335. }());
  93336. BABYLON.BouncingBehavior = BouncingBehavior;
  93337. })(BABYLON || (BABYLON = {}));
  93338. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  93339. "use strict";
  93340. var BABYLON;
  93341. (function (BABYLON) {
  93342. var AutoRotationBehavior = /** @class */ (function () {
  93343. function AutoRotationBehavior() {
  93344. this._zoomStopsAnimation = false;
  93345. this._idleRotationSpeed = 0.05;
  93346. this._idleRotationWaitTime = 2000;
  93347. this._idleRotationSpinupTime = 2000;
  93348. this._isPointerDown = false;
  93349. this._lastFrameTime = null;
  93350. this._lastInteractionTime = -Infinity;
  93351. this._cameraRotationSpeed = 0;
  93352. this._lastFrameRadius = 0;
  93353. }
  93354. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  93355. get: function () {
  93356. return "AutoRotation";
  93357. },
  93358. enumerable: true,
  93359. configurable: true
  93360. });
  93361. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  93362. /**
  93363. * Gets the flag that indicates if user zooming should stop animation.
  93364. */
  93365. get: function () {
  93366. return this._zoomStopsAnimation;
  93367. },
  93368. /**
  93369. * Sets the flag that indicates if user zooming should stop animation.
  93370. */
  93371. set: function (flag) {
  93372. this._zoomStopsAnimation = flag;
  93373. },
  93374. enumerable: true,
  93375. configurable: true
  93376. });
  93377. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  93378. /**
  93379. * Gets the default speed at which the camera rotates around the model.
  93380. */
  93381. get: function () {
  93382. return this._idleRotationSpeed;
  93383. },
  93384. /**
  93385. * Sets the default speed at which the camera rotates around the model.
  93386. */
  93387. set: function (speed) {
  93388. this._idleRotationSpeed = speed;
  93389. },
  93390. enumerable: true,
  93391. configurable: true
  93392. });
  93393. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  93394. /**
  93395. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  93396. */
  93397. get: function () {
  93398. return this._idleRotationWaitTime;
  93399. },
  93400. /**
  93401. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  93402. */
  93403. set: function (time) {
  93404. this._idleRotationWaitTime = time;
  93405. },
  93406. enumerable: true,
  93407. configurable: true
  93408. });
  93409. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  93410. /**
  93411. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93412. */
  93413. get: function () {
  93414. return this._idleRotationSpinupTime;
  93415. },
  93416. /**
  93417. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93418. */
  93419. set: function (time) {
  93420. this._idleRotationSpinupTime = time;
  93421. },
  93422. enumerable: true,
  93423. configurable: true
  93424. });
  93425. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  93426. /**
  93427. * Gets a value indicating if the camera is currently rotating because of this behavior
  93428. */
  93429. get: function () {
  93430. return Math.abs(this._cameraRotationSpeed) > 0;
  93431. },
  93432. enumerable: true,
  93433. configurable: true
  93434. });
  93435. AutoRotationBehavior.prototype.init = function () {
  93436. // Do notihng
  93437. };
  93438. AutoRotationBehavior.prototype.attach = function (camera) {
  93439. var _this = this;
  93440. this._attachedCamera = camera;
  93441. var scene = this._attachedCamera.getScene();
  93442. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93443. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93444. _this._isPointerDown = true;
  93445. return;
  93446. }
  93447. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93448. _this._isPointerDown = false;
  93449. }
  93450. });
  93451. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93452. var now = BABYLON.Tools.Now;
  93453. var dt = 0;
  93454. if (_this._lastFrameTime != null) {
  93455. dt = now - _this._lastFrameTime;
  93456. }
  93457. _this._lastFrameTime = now;
  93458. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93459. _this._applyUserInteraction();
  93460. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  93461. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  93462. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  93463. // Step camera rotation by rotation speed
  93464. if (_this._attachedCamera) {
  93465. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  93466. }
  93467. });
  93468. };
  93469. AutoRotationBehavior.prototype.detach = function () {
  93470. if (!this._attachedCamera) {
  93471. return;
  93472. }
  93473. var scene = this._attachedCamera.getScene();
  93474. if (this._onPrePointerObservableObserver) {
  93475. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93476. }
  93477. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93478. this._attachedCamera = null;
  93479. };
  93480. /**
  93481. * Returns true if user is scrolling.
  93482. * @return true if user is scrolling.
  93483. */
  93484. AutoRotationBehavior.prototype._userIsZooming = function () {
  93485. if (!this._attachedCamera) {
  93486. return false;
  93487. }
  93488. return this._attachedCamera.inertialRadiusOffset !== 0;
  93489. };
  93490. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  93491. if (!this._attachedCamera) {
  93492. return false;
  93493. }
  93494. var zoomHasHitLimit = false;
  93495. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  93496. zoomHasHitLimit = true;
  93497. }
  93498. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  93499. this._lastFrameRadius = this._attachedCamera.radius;
  93500. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  93501. };
  93502. /**
  93503. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93504. */
  93505. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  93506. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  93507. this._lastInteractionTime = BABYLON.Tools.Now;
  93508. }
  93509. };
  93510. // Tools
  93511. AutoRotationBehavior.prototype._userIsMoving = function () {
  93512. if (!this._attachedCamera) {
  93513. return false;
  93514. }
  93515. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93516. this._attachedCamera.inertialBetaOffset !== 0 ||
  93517. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93518. this._attachedCamera.inertialPanningX !== 0 ||
  93519. this._attachedCamera.inertialPanningY !== 0 ||
  93520. this._isPointerDown;
  93521. };
  93522. return AutoRotationBehavior;
  93523. }());
  93524. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  93525. })(BABYLON || (BABYLON = {}));
  93526. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  93527. "use strict";
  93528. var BABYLON;
  93529. (function (BABYLON) {
  93530. var NullEngineOptions = /** @class */ (function () {
  93531. function NullEngineOptions() {
  93532. this.renderWidth = 512;
  93533. this.renderHeight = 256;
  93534. this.textureSize = 512;
  93535. this.deterministicLockstep = false;
  93536. this.lockstepMaxSteps = 4;
  93537. }
  93538. return NullEngineOptions;
  93539. }());
  93540. BABYLON.NullEngineOptions = NullEngineOptions;
  93541. /**
  93542. * The null engine class provides support for headless version of babylon.js.
  93543. * This can be used in server side scenario or for testing purposes
  93544. */
  93545. var NullEngine = /** @class */ (function (_super) {
  93546. __extends(NullEngine, _super);
  93547. function NullEngine(options) {
  93548. if (options === void 0) { options = new NullEngineOptions(); }
  93549. var _this = _super.call(this, null) || this;
  93550. if (options.deterministicLockstep === undefined) {
  93551. options.deterministicLockstep = false;
  93552. }
  93553. if (options.lockstepMaxSteps === undefined) {
  93554. options.lockstepMaxSteps = 4;
  93555. }
  93556. _this._options = options;
  93557. // Init caps
  93558. // We consider we are on a webgl1 capable device
  93559. _this._caps = new BABYLON.EngineCapabilities();
  93560. _this._caps.maxTexturesImageUnits = 16;
  93561. _this._caps.maxVertexTextureImageUnits = 16;
  93562. _this._caps.maxTextureSize = 512;
  93563. _this._caps.maxCubemapTextureSize = 512;
  93564. _this._caps.maxRenderTextureSize = 512;
  93565. _this._caps.maxVertexAttribs = 16;
  93566. _this._caps.maxVaryingVectors = 16;
  93567. _this._caps.maxFragmentUniformVectors = 16;
  93568. _this._caps.maxVertexUniformVectors = 16;
  93569. // Extensions
  93570. _this._caps.standardDerivatives = false;
  93571. _this._caps.astc = null;
  93572. _this._caps.s3tc = null;
  93573. _this._caps.pvrtc = null;
  93574. _this._caps.etc1 = null;
  93575. _this._caps.etc2 = null;
  93576. _this._caps.textureAnisotropicFilterExtension = null;
  93577. _this._caps.maxAnisotropy = 0;
  93578. _this._caps.uintIndices = false;
  93579. _this._caps.fragmentDepthSupported = false;
  93580. _this._caps.highPrecisionShaderSupported = true;
  93581. _this._caps.colorBufferFloat = false;
  93582. _this._caps.textureFloat = false;
  93583. _this._caps.textureFloatLinearFiltering = false;
  93584. _this._caps.textureFloatRender = false;
  93585. _this._caps.textureHalfFloat = false;
  93586. _this._caps.textureHalfFloatLinearFiltering = false;
  93587. _this._caps.textureHalfFloatRender = false;
  93588. _this._caps.textureLOD = false;
  93589. _this._caps.drawBuffersExtension = false;
  93590. _this._caps.depthTextureExtension = false;
  93591. _this._caps.vertexArrayObject = false;
  93592. _this._caps.instancedArrays = false;
  93593. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  93594. // Wrappers
  93595. if (typeof URL === "undefined") {
  93596. URL = {
  93597. createObjectURL: function () { },
  93598. revokeObjectURL: function () { }
  93599. };
  93600. }
  93601. if (typeof Blob === "undefined") {
  93602. Blob = function () { };
  93603. }
  93604. return _this;
  93605. }
  93606. NullEngine.prototype.isDeterministicLockStep = function () {
  93607. return this._options.deterministicLockstep;
  93608. };
  93609. NullEngine.prototype.getLockstepMaxSteps = function () {
  93610. return this._options.lockstepMaxSteps;
  93611. };
  93612. NullEngine.prototype.getHardwareScalingLevel = function () {
  93613. return 1.0;
  93614. };
  93615. NullEngine.prototype.createVertexBuffer = function (vertices) {
  93616. return {
  93617. capacity: 0,
  93618. references: 1,
  93619. is32Bits: false
  93620. };
  93621. };
  93622. NullEngine.prototype.createIndexBuffer = function (indices) {
  93623. return {
  93624. capacity: 0,
  93625. references: 1,
  93626. is32Bits: false
  93627. };
  93628. };
  93629. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  93630. if (stencil === void 0) { stencil = false; }
  93631. };
  93632. NullEngine.prototype.getRenderWidth = function (useScreen) {
  93633. if (useScreen === void 0) { useScreen = false; }
  93634. if (!useScreen && this._currentRenderTarget) {
  93635. return this._currentRenderTarget.width;
  93636. }
  93637. return this._options.renderWidth;
  93638. };
  93639. NullEngine.prototype.getRenderHeight = function (useScreen) {
  93640. if (useScreen === void 0) { useScreen = false; }
  93641. if (!useScreen && this._currentRenderTarget) {
  93642. return this._currentRenderTarget.height;
  93643. }
  93644. return this._options.renderHeight;
  93645. };
  93646. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  93647. this._cachedViewport = viewport;
  93648. };
  93649. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  93650. return {
  93651. transformFeedback: null,
  93652. __SPECTOR_rebuildProgram: null
  93653. };
  93654. };
  93655. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  93656. return [];
  93657. };
  93658. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  93659. return [];
  93660. };
  93661. NullEngine.prototype.bindSamplers = function (effect) {
  93662. this._currentEffect = null;
  93663. };
  93664. NullEngine.prototype.enableEffect = function (effect) {
  93665. this._currentEffect = effect;
  93666. if (effect.onBind) {
  93667. effect.onBind(effect);
  93668. }
  93669. effect.onBindObservable.notifyObservers(effect);
  93670. };
  93671. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  93672. if (zOffset === void 0) { zOffset = 0; }
  93673. if (reverseSide === void 0) { reverseSide = false; }
  93674. };
  93675. NullEngine.prototype.setIntArray = function (uniform, array) {
  93676. };
  93677. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  93678. };
  93679. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  93680. };
  93681. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  93682. };
  93683. NullEngine.prototype.setFloatArray = function (uniform, array) {
  93684. };
  93685. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  93686. };
  93687. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  93688. };
  93689. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  93690. };
  93691. NullEngine.prototype.setArray = function (uniform, array) {
  93692. };
  93693. NullEngine.prototype.setArray2 = function (uniform, array) {
  93694. };
  93695. NullEngine.prototype.setArray3 = function (uniform, array) {
  93696. };
  93697. NullEngine.prototype.setArray4 = function (uniform, array) {
  93698. };
  93699. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  93700. };
  93701. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  93702. };
  93703. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  93704. };
  93705. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  93706. };
  93707. NullEngine.prototype.setFloat = function (uniform, value) {
  93708. };
  93709. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  93710. };
  93711. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  93712. };
  93713. NullEngine.prototype.setBool = function (uniform, bool) {
  93714. };
  93715. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  93716. };
  93717. NullEngine.prototype.setColor3 = function (uniform, color3) {
  93718. };
  93719. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  93720. };
  93721. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  93722. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  93723. if (this._alphaMode === mode) {
  93724. return;
  93725. }
  93726. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  93727. if (!noDepthWriteChange) {
  93728. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  93729. }
  93730. this._alphaMode = mode;
  93731. };
  93732. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  93733. };
  93734. NullEngine.prototype.wipeCaches = function (bruteForce) {
  93735. if (this.preventCacheWipeBetweenFrames) {
  93736. return;
  93737. }
  93738. this.resetTextureCache();
  93739. this._currentEffect = null;
  93740. if (bruteForce) {
  93741. this._currentProgram = null;
  93742. this._stencilState.reset();
  93743. this._depthCullingState.reset();
  93744. this._alphaState.reset();
  93745. }
  93746. this._cachedVertexBuffers = null;
  93747. this._cachedIndexBuffer = null;
  93748. this._cachedEffectForVertexBuffers = null;
  93749. };
  93750. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  93751. };
  93752. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  93753. };
  93754. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  93755. };
  93756. NullEngine.prototype._createTexture = function () {
  93757. return {};
  93758. };
  93759. NullEngine.prototype._releaseTexture = function (texture) {
  93760. };
  93761. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  93762. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93763. if (onLoad === void 0) { onLoad = null; }
  93764. if (onError === void 0) { onError = null; }
  93765. if (buffer === void 0) { buffer = null; }
  93766. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  93767. var url = String(urlArg);
  93768. texture.url = url;
  93769. texture.generateMipMaps = !noMipmap;
  93770. texture.samplingMode = samplingMode;
  93771. texture.invertY = invertY;
  93772. texture.baseWidth = this._options.textureSize;
  93773. texture.baseHeight = this._options.textureSize;
  93774. texture.width = this._options.textureSize;
  93775. texture.height = this._options.textureSize;
  93776. if (format) {
  93777. texture.format = format;
  93778. }
  93779. texture.isReady = true;
  93780. if (onLoad) {
  93781. onLoad();
  93782. }
  93783. return texture;
  93784. };
  93785. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  93786. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  93787. if (options !== undefined && typeof options === "object") {
  93788. fullOptions.generateMipMaps = options.generateMipMaps;
  93789. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  93790. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  93791. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  93792. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  93793. }
  93794. else {
  93795. fullOptions.generateMipMaps = options;
  93796. fullOptions.generateDepthBuffer = true;
  93797. fullOptions.generateStencilBuffer = false;
  93798. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93799. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93800. }
  93801. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  93802. var width = size.width || size;
  93803. var height = size.height || size;
  93804. texture._depthStencilBuffer = {};
  93805. texture._framebuffer = {};
  93806. texture.baseWidth = width;
  93807. texture.baseHeight = height;
  93808. texture.width = width;
  93809. texture.height = height;
  93810. texture.isReady = true;
  93811. texture.samples = 1;
  93812. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  93813. texture.samplingMode = fullOptions.samplingMode;
  93814. texture.type = fullOptions.type;
  93815. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  93816. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  93817. return texture;
  93818. };
  93819. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  93820. texture.samplingMode = samplingMode;
  93821. };
  93822. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  93823. if (this._currentRenderTarget) {
  93824. this.unBindFramebuffer(this._currentRenderTarget);
  93825. }
  93826. this._currentRenderTarget = texture;
  93827. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  93828. if (this._cachedViewport && !forceFullscreenViewport) {
  93829. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  93830. }
  93831. };
  93832. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  93833. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  93834. this._currentRenderTarget = null;
  93835. if (onBeforeUnbind) {
  93836. if (texture._MSAAFramebuffer) {
  93837. this._currentFramebuffer = texture._framebuffer;
  93838. }
  93839. onBeforeUnbind();
  93840. }
  93841. this._currentFramebuffer = null;
  93842. };
  93843. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  93844. var vbo = {
  93845. capacity: 1,
  93846. references: 1,
  93847. is32Bits: false
  93848. };
  93849. return vbo;
  93850. };
  93851. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  93852. if (offset === void 0) { offset = 0; }
  93853. };
  93854. /**
  93855. * Updates a dynamic vertex buffer.
  93856. * @param vertexBuffer the vertex buffer to update
  93857. * @param data the data used to update the vertex buffer
  93858. * @param byteOffset the byte offset of the data (optional)
  93859. * @param byteLength the byte length of the data (optional)
  93860. */
  93861. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  93862. };
  93863. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  93864. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  93865. this._boundTexturesCache[this._activeChannel] = texture;
  93866. }
  93867. };
  93868. NullEngine.prototype._bindTexture = function (channel, texture) {
  93869. if (channel < 0) {
  93870. return;
  93871. }
  93872. this._bindTextureDirectly(0, texture);
  93873. };
  93874. NullEngine.prototype._releaseBuffer = function (buffer) {
  93875. buffer.references--;
  93876. if (buffer.references === 0) {
  93877. return true;
  93878. }
  93879. return false;
  93880. };
  93881. return NullEngine;
  93882. }(BABYLON.Engine));
  93883. BABYLON.NullEngine = NullEngine;
  93884. })(BABYLON || (BABYLON = {}));
  93885. //# sourceMappingURL=babylon.nullEngine.js.map
  93886. "use strict";
  93887. var BABYLON;
  93888. (function (BABYLON) {
  93889. /**
  93890. * This class can be used to get instrumentation data from a Babylon engine
  93891. */
  93892. var EngineInstrumentation = /** @class */ (function () {
  93893. function EngineInstrumentation(engine) {
  93894. this.engine = engine;
  93895. this._captureGPUFrameTime = false;
  93896. this._gpuFrameTime = new BABYLON.PerfCounter();
  93897. this._captureShaderCompilationTime = false;
  93898. this._shaderCompilationTime = new BABYLON.PerfCounter();
  93899. // Observers
  93900. this._onBeginFrameObserver = null;
  93901. this._onEndFrameObserver = null;
  93902. this._onBeforeShaderCompilationObserver = null;
  93903. this._onAfterShaderCompilationObserver = null;
  93904. }
  93905. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  93906. // Properties
  93907. /**
  93908. * Gets the perf counter used for GPU frame time
  93909. */
  93910. get: function () {
  93911. return this._gpuFrameTime;
  93912. },
  93913. enumerable: true,
  93914. configurable: true
  93915. });
  93916. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  93917. /**
  93918. * Gets the GPU frame time capture status
  93919. */
  93920. get: function () {
  93921. return this._captureGPUFrameTime;
  93922. },
  93923. /**
  93924. * Enable or disable the GPU frame time capture
  93925. */
  93926. set: function (value) {
  93927. var _this = this;
  93928. if (value === this._captureGPUFrameTime) {
  93929. return;
  93930. }
  93931. this._captureGPUFrameTime = value;
  93932. if (value) {
  93933. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  93934. if (!_this._gpuFrameTimeToken) {
  93935. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  93936. }
  93937. });
  93938. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  93939. if (!_this._gpuFrameTimeToken) {
  93940. return;
  93941. }
  93942. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  93943. if (time > -1) {
  93944. _this._gpuFrameTimeToken = null;
  93945. _this._gpuFrameTime.fetchNewFrame();
  93946. _this._gpuFrameTime.addCount(time, true);
  93947. }
  93948. });
  93949. }
  93950. else {
  93951. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93952. this._onBeginFrameObserver = null;
  93953. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93954. this._onEndFrameObserver = null;
  93955. }
  93956. },
  93957. enumerable: true,
  93958. configurable: true
  93959. });
  93960. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  93961. /**
  93962. * Gets the perf counter used for shader compilation time
  93963. */
  93964. get: function () {
  93965. return this._shaderCompilationTime;
  93966. },
  93967. enumerable: true,
  93968. configurable: true
  93969. });
  93970. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  93971. /**
  93972. * Gets the shader compilation time capture status
  93973. */
  93974. get: function () {
  93975. return this._captureShaderCompilationTime;
  93976. },
  93977. /**
  93978. * Enable or disable the shader compilation time capture
  93979. */
  93980. set: function (value) {
  93981. var _this = this;
  93982. if (value === this._captureShaderCompilationTime) {
  93983. return;
  93984. }
  93985. this._captureShaderCompilationTime = value;
  93986. if (value) {
  93987. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  93988. _this._shaderCompilationTime.fetchNewFrame();
  93989. _this._shaderCompilationTime.beginMonitoring();
  93990. });
  93991. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  93992. _this._shaderCompilationTime.endMonitoring();
  93993. });
  93994. }
  93995. else {
  93996. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93997. this._onBeforeShaderCompilationObserver = null;
  93998. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93999. this._onAfterShaderCompilationObserver = null;
  94000. }
  94001. },
  94002. enumerable: true,
  94003. configurable: true
  94004. });
  94005. EngineInstrumentation.prototype.dispose = function () {
  94006. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94007. this._onBeginFrameObserver = null;
  94008. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94009. this._onEndFrameObserver = null;
  94010. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94011. this._onBeforeShaderCompilationObserver = null;
  94012. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94013. this._onAfterShaderCompilationObserver = null;
  94014. this.engine = null;
  94015. };
  94016. return EngineInstrumentation;
  94017. }());
  94018. BABYLON.EngineInstrumentation = EngineInstrumentation;
  94019. })(BABYLON || (BABYLON = {}));
  94020. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  94021. "use strict";
  94022. var BABYLON;
  94023. (function (BABYLON) {
  94024. /**
  94025. * This class can be used to get instrumentation data from a Babylon engine
  94026. */
  94027. var SceneInstrumentation = /** @class */ (function () {
  94028. function SceneInstrumentation(scene) {
  94029. var _this = this;
  94030. this.scene = scene;
  94031. this._captureActiveMeshesEvaluationTime = false;
  94032. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  94033. this._captureRenderTargetsRenderTime = false;
  94034. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  94035. this._captureFrameTime = false;
  94036. this._frameTime = new BABYLON.PerfCounter();
  94037. this._captureRenderTime = false;
  94038. this._renderTime = new BABYLON.PerfCounter();
  94039. this._captureInterFrameTime = false;
  94040. this._interFrameTime = new BABYLON.PerfCounter();
  94041. this._captureParticlesRenderTime = false;
  94042. this._particlesRenderTime = new BABYLON.PerfCounter();
  94043. this._captureSpritesRenderTime = false;
  94044. this._spritesRenderTime = new BABYLON.PerfCounter();
  94045. this._capturePhysicsTime = false;
  94046. this._physicsTime = new BABYLON.PerfCounter();
  94047. this._captureAnimationsTime = false;
  94048. this._animationsTime = new BABYLON.PerfCounter();
  94049. // Observers
  94050. this._onBeforeActiveMeshesEvaluationObserver = null;
  94051. this._onAfterActiveMeshesEvaluationObserver = null;
  94052. this._onBeforeRenderTargetsRenderObserver = null;
  94053. this._onAfterRenderTargetsRenderObserver = null;
  94054. this._onAfterRenderObserver = null;
  94055. this._onBeforeDrawPhaseObserver = null;
  94056. this._onAfterDrawPhaseObserver = null;
  94057. this._onBeforeAnimationsObserver = null;
  94058. this._onBeforeParticlesRenderingObserver = null;
  94059. this._onAfterParticlesRenderingObserver = null;
  94060. this._onBeforeSpritesRenderingObserver = null;
  94061. this._onAfterSpritesRenderingObserver = null;
  94062. this._onBeforePhysicsObserver = null;
  94063. this._onAfterPhysicsObserver = null;
  94064. this._onAfterAnimationsObserver = null;
  94065. // Before render
  94066. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  94067. if (_this._captureActiveMeshesEvaluationTime) {
  94068. _this._activeMeshesEvaluationTime.fetchNewFrame();
  94069. }
  94070. if (_this._captureRenderTargetsRenderTime) {
  94071. _this._renderTargetsRenderTime.fetchNewFrame();
  94072. }
  94073. if (_this._captureFrameTime) {
  94074. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  94075. _this._frameTime.beginMonitoring();
  94076. }
  94077. if (_this._captureInterFrameTime) {
  94078. _this._interFrameTime.endMonitoring();
  94079. }
  94080. if (_this._captureParticlesRenderTime) {
  94081. _this._particlesRenderTime.fetchNewFrame();
  94082. }
  94083. if (_this._captureSpritesRenderTime) {
  94084. _this._spritesRenderTime.fetchNewFrame();
  94085. }
  94086. if (_this._captureAnimationsTime) {
  94087. _this._animationsTime.beginMonitoring();
  94088. }
  94089. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  94090. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  94091. });
  94092. // After render
  94093. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  94094. if (_this._captureFrameTime) {
  94095. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  94096. _this._frameTime.endMonitoring();
  94097. }
  94098. if (_this._captureRenderTime) {
  94099. _this._renderTime.endMonitoring(false);
  94100. }
  94101. if (_this._captureInterFrameTime) {
  94102. _this._interFrameTime.beginMonitoring();
  94103. }
  94104. });
  94105. }
  94106. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  94107. // Properties
  94108. /**
  94109. * Gets the perf counter used for active meshes evaluation time
  94110. */
  94111. get: function () {
  94112. return this._activeMeshesEvaluationTime;
  94113. },
  94114. enumerable: true,
  94115. configurable: true
  94116. });
  94117. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  94118. /**
  94119. * Gets the active meshes evaluation time capture status
  94120. */
  94121. get: function () {
  94122. return this._captureActiveMeshesEvaluationTime;
  94123. },
  94124. /**
  94125. * Enable or disable the active meshes evaluation time capture
  94126. */
  94127. set: function (value) {
  94128. var _this = this;
  94129. if (value === this._captureActiveMeshesEvaluationTime) {
  94130. return;
  94131. }
  94132. this._captureActiveMeshesEvaluationTime = value;
  94133. if (value) {
  94134. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  94135. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  94136. _this._activeMeshesEvaluationTime.beginMonitoring();
  94137. });
  94138. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  94139. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  94140. _this._activeMeshesEvaluationTime.endMonitoring();
  94141. });
  94142. }
  94143. else {
  94144. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94145. this._onBeforeActiveMeshesEvaluationObserver = null;
  94146. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94147. this._onAfterActiveMeshesEvaluationObserver = null;
  94148. }
  94149. },
  94150. enumerable: true,
  94151. configurable: true
  94152. });
  94153. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  94154. /**
  94155. * Gets the perf counter used for render targets render time
  94156. */
  94157. get: function () {
  94158. return this._renderTargetsRenderTime;
  94159. },
  94160. enumerable: true,
  94161. configurable: true
  94162. });
  94163. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  94164. /**
  94165. * Gets the render targets render time capture status
  94166. */
  94167. get: function () {
  94168. return this._captureRenderTargetsRenderTime;
  94169. },
  94170. /**
  94171. * Enable or disable the render targets render time capture
  94172. */
  94173. set: function (value) {
  94174. var _this = this;
  94175. if (value === this._captureRenderTargetsRenderTime) {
  94176. return;
  94177. }
  94178. this._captureRenderTargetsRenderTime = value;
  94179. if (value) {
  94180. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  94181. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  94182. _this._renderTargetsRenderTime.beginMonitoring();
  94183. });
  94184. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  94185. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  94186. _this._renderTargetsRenderTime.endMonitoring(false);
  94187. });
  94188. }
  94189. else {
  94190. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94191. this._onBeforeRenderTargetsRenderObserver = null;
  94192. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94193. this._onAfterRenderTargetsRenderObserver = null;
  94194. }
  94195. },
  94196. enumerable: true,
  94197. configurable: true
  94198. });
  94199. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  94200. /**
  94201. * Gets the perf counter used for particles render time
  94202. */
  94203. get: function () {
  94204. return this._particlesRenderTime;
  94205. },
  94206. enumerable: true,
  94207. configurable: true
  94208. });
  94209. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94210. /**
  94211. * Gets the particles render time capture status
  94212. */
  94213. get: function () {
  94214. return this._captureParticlesRenderTime;
  94215. },
  94216. /**
  94217. * Enable or disable the particles render time capture
  94218. */
  94219. set: function (value) {
  94220. var _this = this;
  94221. if (value === this._captureParticlesRenderTime) {
  94222. return;
  94223. }
  94224. this._captureParticlesRenderTime = value;
  94225. if (value) {
  94226. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94227. BABYLON.Tools.StartPerformanceCounter("Particles");
  94228. _this._particlesRenderTime.beginMonitoring();
  94229. });
  94230. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94231. BABYLON.Tools.EndPerformanceCounter("Particles");
  94232. _this._particlesRenderTime.endMonitoring(false);
  94233. });
  94234. }
  94235. else {
  94236. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94237. this._onBeforeParticlesRenderingObserver = null;
  94238. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94239. this._onAfterParticlesRenderingObserver = null;
  94240. }
  94241. },
  94242. enumerable: true,
  94243. configurable: true
  94244. });
  94245. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94246. /**
  94247. * Gets the perf counter used for sprites render time
  94248. */
  94249. get: function () {
  94250. return this._spritesRenderTime;
  94251. },
  94252. enumerable: true,
  94253. configurable: true
  94254. });
  94255. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94256. /**
  94257. * Gets the sprites render time capture status
  94258. */
  94259. get: function () {
  94260. return this._captureSpritesRenderTime;
  94261. },
  94262. /**
  94263. * Enable or disable the sprites render time capture
  94264. */
  94265. set: function (value) {
  94266. var _this = this;
  94267. if (value === this._captureSpritesRenderTime) {
  94268. return;
  94269. }
  94270. this._captureSpritesRenderTime = value;
  94271. if (value) {
  94272. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94273. BABYLON.Tools.StartPerformanceCounter("Sprites");
  94274. _this._spritesRenderTime.beginMonitoring();
  94275. });
  94276. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  94277. BABYLON.Tools.EndPerformanceCounter("Sprites");
  94278. _this._spritesRenderTime.endMonitoring(false);
  94279. });
  94280. }
  94281. else {
  94282. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94283. this._onBeforeSpritesRenderingObserver = null;
  94284. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94285. this._onAfterSpritesRenderingObserver = null;
  94286. }
  94287. },
  94288. enumerable: true,
  94289. configurable: true
  94290. });
  94291. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  94292. /**
  94293. * Gets the perf counter used for physics time
  94294. */
  94295. get: function () {
  94296. return this._physicsTime;
  94297. },
  94298. enumerable: true,
  94299. configurable: true
  94300. });
  94301. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  94302. /**
  94303. * Gets the physics time capture status
  94304. */
  94305. get: function () {
  94306. return this._capturePhysicsTime;
  94307. },
  94308. /**
  94309. * Enable or disable the physics time capture
  94310. */
  94311. set: function (value) {
  94312. var _this = this;
  94313. if (value === this._capturePhysicsTime) {
  94314. return;
  94315. }
  94316. this._capturePhysicsTime = value;
  94317. if (value) {
  94318. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  94319. BABYLON.Tools.StartPerformanceCounter("Physics");
  94320. _this._physicsTime.beginMonitoring();
  94321. });
  94322. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  94323. BABYLON.Tools.EndPerformanceCounter("Physics");
  94324. _this._physicsTime.endMonitoring();
  94325. });
  94326. }
  94327. else {
  94328. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94329. this._onBeforePhysicsObserver = null;
  94330. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94331. this._onAfterPhysicsObserver = null;
  94332. }
  94333. },
  94334. enumerable: true,
  94335. configurable: true
  94336. });
  94337. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  94338. /**
  94339. * Gets the perf counter used for animations time
  94340. */
  94341. get: function () {
  94342. return this._animationsTime;
  94343. },
  94344. enumerable: true,
  94345. configurable: true
  94346. });
  94347. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  94348. /**
  94349. * Gets the animations time capture status
  94350. */
  94351. get: function () {
  94352. return this._captureAnimationsTime;
  94353. },
  94354. /**
  94355. * Enable or disable the animations time capture
  94356. */
  94357. set: function (value) {
  94358. var _this = this;
  94359. if (value === this._captureAnimationsTime) {
  94360. return;
  94361. }
  94362. this._captureAnimationsTime = value;
  94363. if (value) {
  94364. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  94365. _this._animationsTime.endMonitoring();
  94366. });
  94367. }
  94368. else {
  94369. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94370. this._onAfterAnimationsObserver = null;
  94371. }
  94372. },
  94373. enumerable: true,
  94374. configurable: true
  94375. });
  94376. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  94377. /**
  94378. * Gets the perf counter used for frame time capture
  94379. */
  94380. get: function () {
  94381. return this._frameTime;
  94382. },
  94383. enumerable: true,
  94384. configurable: true
  94385. });
  94386. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  94387. /**
  94388. * Gets the frame time capture status
  94389. */
  94390. get: function () {
  94391. return this._captureFrameTime;
  94392. },
  94393. /**
  94394. * Enable or disable the frame time capture
  94395. */
  94396. set: function (value) {
  94397. this._captureFrameTime = value;
  94398. },
  94399. enumerable: true,
  94400. configurable: true
  94401. });
  94402. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  94403. /**
  94404. * Gets the perf counter used for inter-frames time capture
  94405. */
  94406. get: function () {
  94407. return this._interFrameTime;
  94408. },
  94409. enumerable: true,
  94410. configurable: true
  94411. });
  94412. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  94413. /**
  94414. * Gets the inter-frames time capture status
  94415. */
  94416. get: function () {
  94417. return this._captureInterFrameTime;
  94418. },
  94419. /**
  94420. * Enable or disable the inter-frames time capture
  94421. */
  94422. set: function (value) {
  94423. this._captureInterFrameTime = value;
  94424. },
  94425. enumerable: true,
  94426. configurable: true
  94427. });
  94428. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  94429. /**
  94430. * Gets the perf counter used for render time capture
  94431. */
  94432. get: function () {
  94433. return this._renderTime;
  94434. },
  94435. enumerable: true,
  94436. configurable: true
  94437. });
  94438. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  94439. /**
  94440. * Gets the render time capture status
  94441. */
  94442. get: function () {
  94443. return this._captureRenderTime;
  94444. },
  94445. /**
  94446. * Enable or disable the render time capture
  94447. */
  94448. set: function (value) {
  94449. var _this = this;
  94450. if (value === this._captureRenderTime) {
  94451. return;
  94452. }
  94453. this._captureRenderTime = value;
  94454. if (value) {
  94455. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  94456. _this._renderTime.beginMonitoring();
  94457. BABYLON.Tools.StartPerformanceCounter("Main render");
  94458. });
  94459. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  94460. _this._renderTime.endMonitoring(false);
  94461. BABYLON.Tools.EndPerformanceCounter("Main render");
  94462. });
  94463. }
  94464. else {
  94465. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94466. this._onBeforeDrawPhaseObserver = null;
  94467. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94468. this._onAfterDrawPhaseObserver = null;
  94469. }
  94470. },
  94471. enumerable: true,
  94472. configurable: true
  94473. });
  94474. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  94475. /**
  94476. * Gets the perf counter used for draw calls
  94477. */
  94478. get: function () {
  94479. return this.scene.getEngine()._drawCalls;
  94480. },
  94481. enumerable: true,
  94482. configurable: true
  94483. });
  94484. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  94485. /**
  94486. * Gets the perf counter used for texture collisions
  94487. */
  94488. get: function () {
  94489. return this.scene.getEngine()._textureCollisions;
  94490. },
  94491. enumerable: true,
  94492. configurable: true
  94493. });
  94494. SceneInstrumentation.prototype.dispose = function () {
  94495. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94496. this._onAfterRenderObserver = null;
  94497. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94498. this._onBeforeActiveMeshesEvaluationObserver = null;
  94499. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94500. this._onAfterActiveMeshesEvaluationObserver = null;
  94501. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94502. this._onBeforeRenderTargetsRenderObserver = null;
  94503. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94504. this._onAfterRenderTargetsRenderObserver = null;
  94505. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  94506. this._onBeforeAnimationsObserver = null;
  94507. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94508. this._onBeforeParticlesRenderingObserver = null;
  94509. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94510. this._onAfterParticlesRenderingObserver = null;
  94511. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94512. this._onBeforeSpritesRenderingObserver = null;
  94513. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94514. this._onAfterSpritesRenderingObserver = null;
  94515. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94516. this._onBeforeDrawPhaseObserver = null;
  94517. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  94518. this._onAfterDrawPhaseObserver = null;
  94519. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94520. this._onBeforePhysicsObserver = null;
  94521. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94522. this._onAfterPhysicsObserver = null;
  94523. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94524. this._onAfterAnimationsObserver = null;
  94525. this.scene = null;
  94526. };
  94527. return SceneInstrumentation;
  94528. }());
  94529. BABYLON.SceneInstrumentation = SceneInstrumentation;
  94530. })(BABYLON || (BABYLON = {}));
  94531. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  94532. "use strict";
  94533. var BABYLON;
  94534. (function (BABYLON) {
  94535. var _TimeToken = /** @class */ (function () {
  94536. function _TimeToken() {
  94537. this._timeElapsedQueryEnded = false;
  94538. }
  94539. return _TimeToken;
  94540. }());
  94541. BABYLON._TimeToken = _TimeToken;
  94542. })(BABYLON || (BABYLON = {}));
  94543. //# sourceMappingURL=babylon.timeToken.js.map
  94544. "use strict";
  94545. var BABYLON;
  94546. (function (BABYLON) {
  94547. /**
  94548. * Background material defines definition.
  94549. * @ignore Mainly internal Use
  94550. */
  94551. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  94552. __extends(BackgroundMaterialDefines, _super);
  94553. /**
  94554. * Constructor of the defines.
  94555. */
  94556. function BackgroundMaterialDefines() {
  94557. var _this = _super.call(this) || this;
  94558. /**
  94559. * True if the diffuse texture is in use.
  94560. */
  94561. _this.DIFFUSE = false;
  94562. /**
  94563. * The direct UV channel to use.
  94564. */
  94565. _this.DIFFUSEDIRECTUV = 0;
  94566. /**
  94567. * True if the diffuse texture is in gamma space.
  94568. */
  94569. _this.GAMMADIFFUSE = false;
  94570. /**
  94571. * True if the diffuse texture has opacity in the alpha channel.
  94572. */
  94573. _this.DIFFUSEHASALPHA = false;
  94574. /**
  94575. * True if you want the material to fade to transparent at grazing angle.
  94576. */
  94577. _this.OPACITYFRESNEL = false;
  94578. /**
  94579. * True if an extra blur needs to be added in the reflection.
  94580. */
  94581. _this.REFLECTIONBLUR = false;
  94582. /**
  94583. * True if you want the material to fade to reflection at grazing angle.
  94584. */
  94585. _this.REFLECTIONFRESNEL = false;
  94586. /**
  94587. * True if you want the material to falloff as far as you move away from the scene center.
  94588. */
  94589. _this.REFLECTIONFALLOFF = false;
  94590. /**
  94591. * False if the current Webgl implementation does not support the texture lod extension.
  94592. */
  94593. _this.TEXTURELODSUPPORT = false;
  94594. /**
  94595. * True to ensure the data are premultiplied.
  94596. */
  94597. _this.PREMULTIPLYALPHA = false;
  94598. /**
  94599. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  94600. */
  94601. _this.USERGBCOLOR = false;
  94602. /**
  94603. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  94604. * stays aligned with the desired configuration.
  94605. */
  94606. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  94607. /**
  94608. * True to add noise in order to reduce the banding effect.
  94609. */
  94610. _this.NOISE = false;
  94611. /**
  94612. * is the reflection texture in BGR color scheme?
  94613. * Mainly used to solve a bug in ios10 video tag
  94614. */
  94615. _this.REFLECTIONBGR = false;
  94616. _this.IMAGEPROCESSING = false;
  94617. _this.VIGNETTE = false;
  94618. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  94619. _this.VIGNETTEBLENDMODEOPAQUE = false;
  94620. _this.TONEMAPPING = false;
  94621. _this.CONTRAST = false;
  94622. _this.COLORCURVES = false;
  94623. _this.COLORGRADING = false;
  94624. _this.COLORGRADING3D = false;
  94625. _this.SAMPLER3DGREENDEPTH = false;
  94626. _this.SAMPLER3DBGRMAP = false;
  94627. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  94628. _this.EXPOSURE = false;
  94629. // Reflection.
  94630. _this.REFLECTION = false;
  94631. _this.REFLECTIONMAP_3D = false;
  94632. _this.REFLECTIONMAP_SPHERICAL = false;
  94633. _this.REFLECTIONMAP_PLANAR = false;
  94634. _this.REFLECTIONMAP_CUBIC = false;
  94635. _this.REFLECTIONMAP_PROJECTION = false;
  94636. _this.REFLECTIONMAP_SKYBOX = false;
  94637. _this.REFLECTIONMAP_EXPLICIT = false;
  94638. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94639. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94640. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94641. _this.INVERTCUBICMAP = false;
  94642. _this.REFLECTIONMAP_OPPOSITEZ = false;
  94643. _this.LODINREFLECTIONALPHA = false;
  94644. _this.GAMMAREFLECTION = false;
  94645. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  94646. // Default BJS.
  94647. _this.MAINUV1 = false;
  94648. _this.MAINUV2 = false;
  94649. _this.UV1 = false;
  94650. _this.UV2 = false;
  94651. _this.CLIPPLANE = false;
  94652. _this.POINTSIZE = false;
  94653. _this.FOG = false;
  94654. _this.NORMAL = false;
  94655. _this.NUM_BONE_INFLUENCERS = 0;
  94656. _this.BonesPerMesh = 0;
  94657. _this.INSTANCES = false;
  94658. _this.SHADOWFLOAT = false;
  94659. _this.rebuild();
  94660. return _this;
  94661. }
  94662. return BackgroundMaterialDefines;
  94663. }(BABYLON.MaterialDefines));
  94664. /**
  94665. * Background material used to create an efficient environement around your scene.
  94666. */
  94667. var BackgroundMaterial = /** @class */ (function (_super) {
  94668. __extends(BackgroundMaterial, _super);
  94669. /**
  94670. * Instantiates a Background Material in the given scene
  94671. * @param name The friendly name of the material
  94672. * @param scene The scene to add the material to
  94673. */
  94674. function BackgroundMaterial(name, scene) {
  94675. var _this = _super.call(this, name, scene) || this;
  94676. /**
  94677. * Key light Color (multiply against the environement texture)
  94678. */
  94679. _this.primaryColor = BABYLON.Color3.White();
  94680. _this._primaryColorShadowLevel = 0;
  94681. _this._primaryColorHighlightLevel = 0;
  94682. /**
  94683. * Reflection Texture used in the material.
  94684. * Should be author in a specific way for the best result (refer to the documentation).
  94685. */
  94686. _this.reflectionTexture = null;
  94687. /**
  94688. * Reflection Texture level of blur.
  94689. *
  94690. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  94691. * texture twice.
  94692. */
  94693. _this.reflectionBlur = 0;
  94694. /**
  94695. * Diffuse Texture used in the material.
  94696. * Should be author in a specific way for the best result (refer to the documentation).
  94697. */
  94698. _this.diffuseTexture = null;
  94699. _this._shadowLights = null;
  94700. /**
  94701. * Specify the list of lights casting shadow on the material.
  94702. * All scene shadow lights will be included if null.
  94703. */
  94704. _this.shadowLights = null;
  94705. /**
  94706. * Helps adjusting the shadow to a softer level if required.
  94707. * 0 means black shadows and 1 means no shadows.
  94708. */
  94709. _this.shadowLevel = 0;
  94710. /**
  94711. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  94712. * It is usually zero but might be interesting to modify according to your setup.
  94713. */
  94714. _this.sceneCenter = BABYLON.Vector3.Zero();
  94715. /**
  94716. * This helps specifying that the material is falling off to the sky box at grazing angle.
  94717. * This helps ensuring a nice transition when the camera goes under the ground.
  94718. */
  94719. _this.opacityFresnel = true;
  94720. /**
  94721. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  94722. * This helps adding a mirror texture on the ground.
  94723. */
  94724. _this.reflectionFresnel = false;
  94725. /**
  94726. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  94727. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  94728. */
  94729. _this.reflectionFalloffDistance = 0.0;
  94730. /**
  94731. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  94732. */
  94733. _this.reflectionAmount = 1.0;
  94734. /**
  94735. * This specifies the weight of the reflection at grazing angle.
  94736. */
  94737. _this.reflectionReflectance0 = 0.05;
  94738. /**
  94739. * This specifies the weight of the reflection at a perpendicular point of view.
  94740. */
  94741. _this.reflectionReflectance90 = 0.5;
  94742. /**
  94743. * Helps to directly use the maps channels instead of their level.
  94744. */
  94745. _this.useRGBColor = true;
  94746. /**
  94747. * This helps reducing the banding effect that could occur on the background.
  94748. */
  94749. _this.enableNoise = false;
  94750. _this._fovMultiplier = 1.0;
  94751. /**
  94752. * Enable the FOV adjustment feature controlled by fovMultiplier.
  94753. */
  94754. _this.useEquirectangularFOV = false;
  94755. _this._maxSimultaneousLights = 4;
  94756. /**
  94757. * Number of Simultaneous lights allowed on the material.
  94758. */
  94759. _this.maxSimultaneousLights = 4;
  94760. /**
  94761. * Keep track of the image processing observer to allow dispose and replace.
  94762. */
  94763. _this._imageProcessingObserver = null;
  94764. /**
  94765. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  94766. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  94767. */
  94768. _this.switchToBGR = false;
  94769. // Temp values kept as cache in the material.
  94770. _this._renderTargets = new BABYLON.SmartArray(16);
  94771. _this._reflectionControls = BABYLON.Vector4.Zero();
  94772. _this._white = BABYLON.Color3.White();
  94773. _this._primaryShadowColor = BABYLON.Color3.Black();
  94774. _this._primaryHighlightColor = BABYLON.Color3.Black();
  94775. // Setup the default processing configuration to the scene.
  94776. _this._attachImageProcessingConfiguration(null);
  94777. _this.getRenderTargetTextures = function () {
  94778. _this._renderTargets.reset();
  94779. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  94780. _this._renderTargets.push(_this._diffuseTexture);
  94781. }
  94782. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  94783. _this._renderTargets.push(_this._reflectionTexture);
  94784. }
  94785. return _this._renderTargets;
  94786. };
  94787. return _this;
  94788. }
  94789. Object.defineProperty(BackgroundMaterial.prototype, "perceptualColor", {
  94790. /**
  94791. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  94792. * This acts as a helper to set the primary color to a more "human friendly" value.
  94793. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  94794. * output color as close as possible from the chosen value.
  94795. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  94796. * part of lighting setup.)
  94797. */
  94798. get: function () {
  94799. return this._perceptualColor;
  94800. },
  94801. set: function (value) {
  94802. this._perceptualColor = value;
  94803. this._computePrimaryColorFromPerceptualColor();
  94804. this._markAllSubMeshesAsLightsDirty();
  94805. },
  94806. enumerable: true,
  94807. configurable: true
  94808. });
  94809. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  94810. /**
  94811. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  94812. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  94813. */
  94814. get: function () {
  94815. return this._primaryColorShadowLevel;
  94816. },
  94817. set: function (value) {
  94818. this._primaryColorShadowLevel = value;
  94819. this._computePrimaryColors();
  94820. this._markAllSubMeshesAsLightsDirty();
  94821. },
  94822. enumerable: true,
  94823. configurable: true
  94824. });
  94825. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  94826. /**
  94827. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  94828. * The primary color is used at the level chosen to define what the white area would look.
  94829. */
  94830. get: function () {
  94831. return this._primaryColorHighlightLevel;
  94832. },
  94833. set: function (value) {
  94834. this._primaryColorHighlightLevel = value;
  94835. this._computePrimaryColors();
  94836. this._markAllSubMeshesAsLightsDirty();
  94837. },
  94838. enumerable: true,
  94839. configurable: true
  94840. });
  94841. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  94842. /**
  94843. * Sets the reflection reflectance fresnel values according to the default standard
  94844. * empirically know to work well :-)
  94845. */
  94846. set: function (value) {
  94847. var reflectionWeight = value;
  94848. if (reflectionWeight < 0.5) {
  94849. reflectionWeight = reflectionWeight * 2.0;
  94850. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  94851. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  94852. }
  94853. else {
  94854. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  94855. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  94856. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  94857. }
  94858. },
  94859. enumerable: true,
  94860. configurable: true
  94861. });
  94862. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  94863. /**
  94864. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94865. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  94866. * Recommended to be keep at 1.0 except for special cases.
  94867. */
  94868. get: function () {
  94869. return this._fovMultiplier;
  94870. },
  94871. set: function (value) {
  94872. if (isNaN(value)) {
  94873. value = 1.0;
  94874. }
  94875. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  94876. },
  94877. enumerable: true,
  94878. configurable: true
  94879. });
  94880. /**
  94881. * Attaches a new image processing configuration to the PBR Material.
  94882. * @param configuration (if null the scene configuration will be use)
  94883. */
  94884. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  94885. var _this = this;
  94886. if (configuration === this._imageProcessingConfiguration) {
  94887. return;
  94888. }
  94889. // Detaches observer.
  94890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94892. }
  94893. // Pick the scene configuration if needed.
  94894. if (!configuration) {
  94895. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  94896. }
  94897. else {
  94898. this._imageProcessingConfiguration = configuration;
  94899. }
  94900. // Attaches observer.
  94901. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  94902. _this._computePrimaryColorFromPerceptualColor();
  94903. _this._markAllSubMeshesAsImageProcessingDirty();
  94904. });
  94905. };
  94906. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  94907. /**
  94908. * Gets the image processing configuration used either in this material.
  94909. */
  94910. get: function () {
  94911. return this._imageProcessingConfiguration;
  94912. },
  94913. /**
  94914. * Sets the Default image processing configuration used either in the this material.
  94915. *
  94916. * If sets to null, the scene one is in use.
  94917. */
  94918. set: function (value) {
  94919. this._attachImageProcessingConfiguration(value);
  94920. // Ensure the effect will be rebuilt.
  94921. this._markAllSubMeshesAsTexturesDirty();
  94922. },
  94923. enumerable: true,
  94924. configurable: true
  94925. });
  94926. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  94927. /**
  94928. * Gets wether the color curves effect is enabled.
  94929. */
  94930. get: function () {
  94931. return this.imageProcessingConfiguration.colorCurvesEnabled;
  94932. },
  94933. /**
  94934. * Sets wether the color curves effect is enabled.
  94935. */
  94936. set: function (value) {
  94937. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  94938. },
  94939. enumerable: true,
  94940. configurable: true
  94941. });
  94942. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  94943. /**
  94944. * Gets wether the color grading effect is enabled.
  94945. */
  94946. get: function () {
  94947. return this.imageProcessingConfiguration.colorGradingEnabled;
  94948. },
  94949. /**
  94950. * Gets wether the color grading effect is enabled.
  94951. */
  94952. set: function (value) {
  94953. this.imageProcessingConfiguration.colorGradingEnabled = value;
  94954. },
  94955. enumerable: true,
  94956. configurable: true
  94957. });
  94958. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  94959. /**
  94960. * Gets wether tonemapping is enabled or not.
  94961. */
  94962. get: function () {
  94963. return this._imageProcessingConfiguration.toneMappingEnabled;
  94964. },
  94965. /**
  94966. * Sets wether tonemapping is enabled or not
  94967. */
  94968. set: function (value) {
  94969. this._imageProcessingConfiguration.toneMappingEnabled = value;
  94970. },
  94971. enumerable: true,
  94972. configurable: true
  94973. });
  94974. ;
  94975. ;
  94976. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  94977. /**
  94978. * The camera exposure used on this material.
  94979. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94980. * This corresponds to a photographic exposure.
  94981. */
  94982. get: function () {
  94983. return this._imageProcessingConfiguration.exposure;
  94984. },
  94985. /**
  94986. * The camera exposure used on this material.
  94987. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94988. * This corresponds to a photographic exposure.
  94989. */
  94990. set: function (value) {
  94991. this._imageProcessingConfiguration.exposure = value;
  94992. },
  94993. enumerable: true,
  94994. configurable: true
  94995. });
  94996. ;
  94997. ;
  94998. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  94999. /**
  95000. * Gets The camera contrast used on this material.
  95001. */
  95002. get: function () {
  95003. return this._imageProcessingConfiguration.contrast;
  95004. },
  95005. /**
  95006. * Sets The camera contrast used on this material.
  95007. */
  95008. set: function (value) {
  95009. this._imageProcessingConfiguration.contrast = value;
  95010. },
  95011. enumerable: true,
  95012. configurable: true
  95013. });
  95014. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  95015. /**
  95016. * Gets the Color Grading 2D Lookup Texture.
  95017. */
  95018. get: function () {
  95019. return this._imageProcessingConfiguration.colorGradingTexture;
  95020. },
  95021. /**
  95022. * Sets the Color Grading 2D Lookup Texture.
  95023. */
  95024. set: function (value) {
  95025. this.imageProcessingConfiguration.colorGradingTexture = value;
  95026. },
  95027. enumerable: true,
  95028. configurable: true
  95029. });
  95030. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  95031. /**
  95032. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95033. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95034. * 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;
  95035. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95036. */
  95037. get: function () {
  95038. return this.imageProcessingConfiguration.colorCurves;
  95039. },
  95040. /**
  95041. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95042. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95043. * 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;
  95044. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95045. */
  95046. set: function (value) {
  95047. this.imageProcessingConfiguration.colorCurves = value;
  95048. },
  95049. enumerable: true,
  95050. configurable: true
  95051. });
  95052. /**
  95053. * The entire material has been created in order to prevent overdraw.
  95054. * @returns false
  95055. */
  95056. BackgroundMaterial.prototype.needAlphaTesting = function () {
  95057. return true;
  95058. };
  95059. /**
  95060. * The entire material has been created in order to prevent overdraw.
  95061. * @returns true if blending is enable
  95062. */
  95063. BackgroundMaterial.prototype.needAlphaBlending = function () {
  95064. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  95065. };
  95066. /**
  95067. * Checks wether the material is ready to be rendered for a given mesh.
  95068. * @param mesh The mesh to render
  95069. * @param subMesh The submesh to check against
  95070. * @param useInstances Specify wether or not the material is used with instances
  95071. * @returns true if all the dependencies are ready (Textures, Effects...)
  95072. */
  95073. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  95074. var _this = this;
  95075. if (useInstances === void 0) { useInstances = false; }
  95076. if (subMesh.effect && this.isFrozen) {
  95077. if (this._wasPreviouslyReady) {
  95078. return true;
  95079. }
  95080. }
  95081. if (!subMesh._materialDefines) {
  95082. subMesh._materialDefines = new BackgroundMaterialDefines();
  95083. }
  95084. var scene = this.getScene();
  95085. var defines = subMesh._materialDefines;
  95086. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  95087. if (defines._renderId === scene.getRenderId()) {
  95088. return true;
  95089. }
  95090. }
  95091. var engine = scene.getEngine();
  95092. // Lights
  95093. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  95094. defines._needNormals = true;
  95095. // Textures
  95096. if (defines._areTexturesDirty) {
  95097. defines._needUVs = false;
  95098. if (scene.texturesEnabled) {
  95099. if (scene.getEngine().getCaps().textureLOD) {
  95100. defines.TEXTURELODSUPPORT = true;
  95101. }
  95102. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95103. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  95104. return false;
  95105. }
  95106. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  95107. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  95108. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  95109. defines.OPACITYFRESNEL = this._opacityFresnel;
  95110. }
  95111. else {
  95112. defines.DIFFUSE = false;
  95113. defines.DIFFUSEHASALPHA = false;
  95114. defines.GAMMADIFFUSE = false;
  95115. defines.OPACITYFRESNEL = false;
  95116. }
  95117. var reflectionTexture = this._reflectionTexture;
  95118. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95119. if (!reflectionTexture.isReadyOrNotBlocking()) {
  95120. return false;
  95121. }
  95122. defines.REFLECTION = true;
  95123. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  95124. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  95125. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  95126. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  95127. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  95128. defines.REFLECTIONBGR = this.switchToBGR;
  95129. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  95130. defines.INVERTCUBICMAP = true;
  95131. }
  95132. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  95133. switch (reflectionTexture.coordinatesMode) {
  95134. case BABYLON.Texture.CUBIC_MODE:
  95135. case BABYLON.Texture.INVCUBIC_MODE:
  95136. defines.REFLECTIONMAP_CUBIC = true;
  95137. break;
  95138. case BABYLON.Texture.EXPLICIT_MODE:
  95139. defines.REFLECTIONMAP_EXPLICIT = true;
  95140. break;
  95141. case BABYLON.Texture.PLANAR_MODE:
  95142. defines.REFLECTIONMAP_PLANAR = true;
  95143. break;
  95144. case BABYLON.Texture.PROJECTION_MODE:
  95145. defines.REFLECTIONMAP_PROJECTION = true;
  95146. break;
  95147. case BABYLON.Texture.SKYBOX_MODE:
  95148. defines.REFLECTIONMAP_SKYBOX = true;
  95149. break;
  95150. case BABYLON.Texture.SPHERICAL_MODE:
  95151. defines.REFLECTIONMAP_SPHERICAL = true;
  95152. break;
  95153. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  95154. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  95155. break;
  95156. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  95157. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  95158. break;
  95159. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  95160. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  95161. break;
  95162. }
  95163. if (this.reflectionFresnel) {
  95164. defines.REFLECTIONFRESNEL = true;
  95165. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  95166. this._reflectionControls.x = this.reflectionAmount;
  95167. this._reflectionControls.y = this.reflectionReflectance0;
  95168. this._reflectionControls.z = this.reflectionReflectance90;
  95169. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  95170. }
  95171. else {
  95172. defines.REFLECTIONFRESNEL = false;
  95173. defines.REFLECTIONFALLOFF = false;
  95174. }
  95175. }
  95176. else {
  95177. defines.REFLECTION = false;
  95178. defines.REFLECTIONFALLOFF = false;
  95179. defines.REFLECTIONBLUR = false;
  95180. defines.REFLECTIONMAP_3D = false;
  95181. defines.REFLECTIONMAP_SPHERICAL = false;
  95182. defines.REFLECTIONMAP_PLANAR = false;
  95183. defines.REFLECTIONMAP_CUBIC = false;
  95184. defines.REFLECTIONMAP_PROJECTION = false;
  95185. defines.REFLECTIONMAP_SKYBOX = false;
  95186. defines.REFLECTIONMAP_EXPLICIT = false;
  95187. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95188. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95189. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95190. defines.INVERTCUBICMAP = false;
  95191. defines.REFLECTIONMAP_OPPOSITEZ = false;
  95192. defines.LODINREFLECTIONALPHA = false;
  95193. defines.GAMMAREFLECTION = false;
  95194. }
  95195. }
  95196. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  95197. defines.USERGBCOLOR = this._useRGBColor;
  95198. defines.NOISE = this._enableNoise;
  95199. }
  95200. if (defines._areLightsDirty) {
  95201. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  95202. }
  95203. if (defines._areImageProcessingDirty) {
  95204. if (!this._imageProcessingConfiguration.isReady()) {
  95205. return false;
  95206. }
  95207. this._imageProcessingConfiguration.prepareDefines(defines);
  95208. }
  95209. // Misc.
  95210. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  95211. // Values that need to be evaluated on every frame
  95212. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  95213. // Attribs
  95214. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  95215. if (mesh) {
  95216. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95217. mesh.createNormals(true);
  95218. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  95219. }
  95220. }
  95221. }
  95222. // Get correct effect
  95223. if (defines.isDirty) {
  95224. defines.markAsProcessed();
  95225. scene.resetCachedMaterial();
  95226. // Fallbacks
  95227. var fallbacks = new BABYLON.EffectFallbacks();
  95228. if (defines.FOG) {
  95229. fallbacks.addFallback(0, "FOG");
  95230. }
  95231. if (defines.POINTSIZE) {
  95232. fallbacks.addFallback(1, "POINTSIZE");
  95233. }
  95234. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  95235. if (defines.NUM_BONE_INFLUENCERS > 0) {
  95236. fallbacks.addCPUSkinningFallback(0, mesh);
  95237. }
  95238. //Attributes
  95239. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95240. if (defines.NORMAL) {
  95241. attribs.push(BABYLON.VertexBuffer.NormalKind);
  95242. }
  95243. if (defines.UV1) {
  95244. attribs.push(BABYLON.VertexBuffer.UVKind);
  95245. }
  95246. if (defines.UV2) {
  95247. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95248. }
  95249. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95250. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95251. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95252. "vFogInfos", "vFogColor", "pointSize",
  95253. "vClipPlane", "mBones",
  95254. "vPrimaryColor", "vPrimaryColorShadow",
  95255. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95256. "shadowLevel", "alpha",
  95257. "vBackgroundCenter", "vReflectionControl",
  95258. "vDiffuseInfos", "diffuseMatrix",
  95259. ];
  95260. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95261. var uniformBuffers = ["Material", "Scene"];
  95262. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95263. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95264. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95265. uniformsNames: uniforms,
  95266. uniformBuffersNames: uniformBuffers,
  95267. samplers: samplers,
  95268. defines: defines,
  95269. maxSimultaneousLights: this._maxSimultaneousLights
  95270. });
  95271. var onCompiled = function (effect) {
  95272. if (_this.onCompiled) {
  95273. _this.onCompiled(effect);
  95274. }
  95275. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  95276. };
  95277. var join = defines.toString();
  95278. subMesh.setEffect(scene.getEngine().createEffect("background", {
  95279. attributes: attribs,
  95280. uniformsNames: uniforms,
  95281. uniformBuffersNames: uniformBuffers,
  95282. samplers: samplers,
  95283. defines: join,
  95284. fallbacks: fallbacks,
  95285. onCompiled: onCompiled,
  95286. onError: this.onError,
  95287. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  95288. }, engine), defines);
  95289. this.buildUniformLayout();
  95290. }
  95291. if (!subMesh.effect || !subMesh.effect.isReady()) {
  95292. return false;
  95293. }
  95294. defines._renderId = scene.getRenderId();
  95295. this._wasPreviouslyReady = true;
  95296. return true;
  95297. };
  95298. /**
  95299. * Compute the primary color according to the chosen perceptual color.
  95300. */
  95301. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  95302. if (!this._perceptualColor) {
  95303. return;
  95304. }
  95305. this._primaryColor.copyFrom(this._perceptualColor);
  95306. // Revert gamma space.
  95307. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  95308. // Revert image processing configuration.
  95309. if (this._imageProcessingConfiguration) {
  95310. // Revert tone mapping.
  95311. if (this._imageProcessingConfiguration.toneMappingEnabled) {
  95312. // shader reference.
  95313. // tonemapped.rgb = 1.0 - exp2(-tonemappingCalibration * color.rgb);
  95314. // providing
  95315. // log2(1.0 - tonemapped.rgb) / -tonemappingCalibration = color.rgb;
  95316. // 1.0 - tonemapped.rgb
  95317. this._white.subtractToRef(this._primaryColor, this._primaryColor);
  95318. // log2(1.0 - tonemapped.rgb)
  95319. this._primaryColor.r = BABYLON.Scalar.Log2(this._primaryColor.r);
  95320. this._primaryColor.g = BABYLON.Scalar.Log2(this._primaryColor.g);
  95321. this._primaryColor.b = BABYLON.Scalar.Log2(this._primaryColor.b);
  95322. // log2(1.0 - tonemapped.rgb) / -tonemappingCalibration
  95323. this._primaryColor.scaleToRef(-1 / BackgroundMaterial._tonemappingCalibration, this._primaryColor);
  95324. }
  95325. // Revert Exposure.
  95326. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  95327. }
  95328. this._computePrimaryColors();
  95329. };
  95330. /**
  95331. * Compute the highlights and shadow colors according to their chosen levels.
  95332. */
  95333. BackgroundMaterial.prototype._computePrimaryColors = function () {
  95334. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  95335. return;
  95336. }
  95337. // Find the highlight color based on the configuration.
  95338. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  95339. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  95340. this._primaryShadowColor.clampToRef(0, 1, this._primaryShadowColor);
  95341. // Find the shadow color based on the configuration.
  95342. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  95343. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  95344. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  95345. this._primaryHighlightColor.clampToRef(0, 1, this._primaryHighlightColor);
  95346. };
  95347. /**
  95348. * Build the uniform buffer used in the material.
  95349. */
  95350. BackgroundMaterial.prototype.buildUniformLayout = function () {
  95351. // Order is important !
  95352. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  95353. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  95354. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  95355. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  95356. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  95357. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  95358. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  95359. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  95360. this._uniformBuffer.addUniform("pointSize", 1);
  95361. this._uniformBuffer.addUniform("shadowLevel", 1);
  95362. this._uniformBuffer.addUniform("alpha", 1);
  95363. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  95364. this._uniformBuffer.addUniform("vReflectionControl", 4);
  95365. this._uniformBuffer.create();
  95366. };
  95367. /**
  95368. * Unbind the material.
  95369. */
  95370. BackgroundMaterial.prototype.unbind = function () {
  95371. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  95372. this._uniformBuffer.setTexture("diffuseSampler", null);
  95373. }
  95374. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  95375. this._uniformBuffer.setTexture("reflectionSampler", null);
  95376. }
  95377. _super.prototype.unbind.call(this);
  95378. };
  95379. /**
  95380. * Bind only the world matrix to the material.
  95381. * @param world The world matrix to bind.
  95382. */
  95383. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  95384. this._activeEffect.setMatrix("world", world);
  95385. };
  95386. /**
  95387. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  95388. * @param world The world matrix to bind.
  95389. * @param subMesh The submesh to bind for.
  95390. */
  95391. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  95392. var scene = this.getScene();
  95393. var defines = subMesh._materialDefines;
  95394. if (!defines) {
  95395. return;
  95396. }
  95397. var effect = subMesh.effect;
  95398. if (!effect) {
  95399. return;
  95400. }
  95401. this._activeEffect = effect;
  95402. // Matrices
  95403. this.bindOnlyWorldMatrix(world);
  95404. // Bones
  95405. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  95406. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  95407. if (mustRebind) {
  95408. this._uniformBuffer.bindToEffect(effect, "Material");
  95409. this.bindViewProjection(effect);
  95410. var reflectionTexture = this._reflectionTexture;
  95411. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  95412. // Texture uniforms
  95413. if (scene.texturesEnabled) {
  95414. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95415. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  95416. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  95417. }
  95418. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95419. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  95420. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  95421. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  95422. }
  95423. }
  95424. if (this.shadowLevel > 0) {
  95425. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  95426. }
  95427. this._uniformBuffer.updateFloat("alpha", this.alpha);
  95428. // Point size
  95429. if (this.pointsCloud) {
  95430. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  95431. }
  95432. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  95433. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  95434. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  95435. }
  95436. else {
  95437. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  95438. }
  95439. }
  95440. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  95441. // Textures
  95442. if (scene.texturesEnabled) {
  95443. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95444. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  95445. }
  95446. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95447. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  95448. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95449. }
  95450. else if (!defines.REFLECTIONBLUR) {
  95451. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95452. }
  95453. else {
  95454. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  95455. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  95456. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  95457. }
  95458. if (defines.REFLECTIONFRESNEL) {
  95459. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  95460. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  95461. }
  95462. }
  95463. }
  95464. // Clip plane
  95465. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  95466. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  95467. }
  95468. if (mustRebind || !this.isFrozen) {
  95469. if (scene.lightsEnabled) {
  95470. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  95471. }
  95472. // View
  95473. this.bindView(effect);
  95474. // Fog
  95475. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  95476. // image processing
  95477. this._imageProcessingConfiguration.bind(this._activeEffect);
  95478. }
  95479. this._uniformBuffer.update();
  95480. this._afterBind(mesh);
  95481. };
  95482. /**
  95483. * Dispose the material.
  95484. * @param forceDisposeEffect Force disposal of the associated effect.
  95485. * @param forceDisposeTextures Force disposal of the associated textures.
  95486. */
  95487. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  95488. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  95489. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  95490. if (forceDisposeTextures) {
  95491. if (this.diffuseTexture) {
  95492. this.diffuseTexture.dispose();
  95493. }
  95494. if (this.reflectionTexture) {
  95495. this.reflectionTexture.dispose();
  95496. }
  95497. }
  95498. this._renderTargets.dispose();
  95499. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95500. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95501. }
  95502. _super.prototype.dispose.call(this, forceDisposeEffect);
  95503. };
  95504. /**
  95505. * Clones the material.
  95506. * @param name The cloned name.
  95507. * @returns The cloned material.
  95508. */
  95509. BackgroundMaterial.prototype.clone = function (name) {
  95510. var _this = this;
  95511. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  95512. };
  95513. /**
  95514. * Serializes the current material to its JSON representation.
  95515. * @returns The JSON representation.
  95516. */
  95517. BackgroundMaterial.prototype.serialize = function () {
  95518. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95519. serializationObject.customType = "BABYLON.BackgroundMaterial";
  95520. return serializationObject;
  95521. };
  95522. /**
  95523. * Gets the class name of the material
  95524. * @returns "BackgroundMaterial"
  95525. */
  95526. BackgroundMaterial.prototype.getClassName = function () {
  95527. return "BackgroundMaterial";
  95528. };
  95529. /**
  95530. * Parse a JSON input to create back a background material.
  95531. * @param source The JSON data to parse
  95532. * @param scene The scene to create the parsed material in
  95533. * @param rootUrl The root url of the assets the material depends upon
  95534. * @returns the instantiated BackgroundMaterial.
  95535. */
  95536. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  95537. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  95538. };
  95539. /**
  95540. * Standard reflectance value at parallel view angle.
  95541. */
  95542. BackgroundMaterial.StandardReflectance0 = 0.05;
  95543. /**
  95544. * Standard reflectance value at grazing angle.
  95545. */
  95546. BackgroundMaterial.StandardReflectance90 = 0.5;
  95547. /**
  95548. * Tone Mapping calibration (should match image processing tone mapping calibration value).
  95549. */
  95550. BackgroundMaterial._tonemappingCalibration = 1.590579;
  95551. __decorate([
  95552. BABYLON.serializeAsColor3()
  95553. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  95554. __decorate([
  95555. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95556. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  95557. __decorate([
  95558. BABYLON.serializeAsColor3()
  95559. ], BackgroundMaterial.prototype, "_perceptualColor", void 0);
  95560. __decorate([
  95561. BABYLON.serialize()
  95562. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  95563. __decorate([
  95564. BABYLON.serialize()
  95565. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  95566. __decorate([
  95567. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  95568. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  95569. __decorate([
  95570. BABYLON.serializeAsTexture()
  95571. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  95572. __decorate([
  95573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95574. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  95575. __decorate([
  95576. BABYLON.serialize()
  95577. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  95578. __decorate([
  95579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95580. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  95581. __decorate([
  95582. BABYLON.serializeAsTexture()
  95583. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  95584. __decorate([
  95585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95586. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  95587. __decorate([
  95588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95589. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  95590. __decorate([
  95591. BABYLON.serialize()
  95592. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  95593. __decorate([
  95594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95595. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  95596. __decorate([
  95597. BABYLON.serializeAsVector3()
  95598. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  95599. __decorate([
  95600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95601. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  95602. __decorate([
  95603. BABYLON.serialize()
  95604. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  95605. __decorate([
  95606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95607. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  95608. __decorate([
  95609. BABYLON.serialize()
  95610. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  95611. __decorate([
  95612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95613. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  95614. __decorate([
  95615. BABYLON.serialize()
  95616. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  95617. __decorate([
  95618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95619. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  95620. __decorate([
  95621. BABYLON.serialize()
  95622. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  95623. __decorate([
  95624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95625. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  95626. __decorate([
  95627. BABYLON.serialize()
  95628. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  95629. __decorate([
  95630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95631. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  95632. __decorate([
  95633. BABYLON.serialize()
  95634. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  95635. __decorate([
  95636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95637. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  95638. __decorate([
  95639. BABYLON.serialize()
  95640. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  95641. __decorate([
  95642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95643. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  95644. __decorate([
  95645. BABYLON.serialize()
  95646. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  95647. __decorate([
  95648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95649. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  95650. __decorate([
  95651. BABYLON.serialize()
  95652. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  95653. __decorate([
  95654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  95655. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  95656. __decorate([
  95657. BABYLON.serializeAsImageProcessingConfiguration()
  95658. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  95659. return BackgroundMaterial;
  95660. }(BABYLON.PushMaterial));
  95661. BABYLON.BackgroundMaterial = BackgroundMaterial;
  95662. })(BABYLON || (BABYLON = {}));
  95663. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  95664. "use strict";
  95665. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95666. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95667. s = arguments[i];
  95668. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95669. t[p] = s[p];
  95670. }
  95671. return t;
  95672. };
  95673. var BABYLON;
  95674. (function (BABYLON) {
  95675. /**
  95676. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  95677. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  95678. * It also helps with the default setup of your imageProcessing configuration.
  95679. */
  95680. var EnvironmentHelper = /** @class */ (function () {
  95681. /**
  95682. * constructor
  95683. * @param options
  95684. * @param scene The scene to add the material to
  95685. */
  95686. function EnvironmentHelper(options, scene) {
  95687. var _this = this;
  95688. this._errorHandler = function (message, exception) {
  95689. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  95690. };
  95691. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  95692. this._scene = scene;
  95693. this.onErrorObservable = new BABYLON.Observable();
  95694. this._setupBackground();
  95695. this._setupImageProcessing();
  95696. }
  95697. /**
  95698. * Creates the default options for the helper.
  95699. */
  95700. EnvironmentHelper._getDefaultOptions = function () {
  95701. return {
  95702. createGround: true,
  95703. groundSize: 15,
  95704. groundTexture: this._groundTextureCDNUrl,
  95705. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95706. groundOpacity: 0.9,
  95707. enableGroundShadow: true,
  95708. groundShadowLevel: 0.5,
  95709. enableGroundMirror: false,
  95710. groundMirrorSizeRatio: 0.3,
  95711. groundMirrorBlurKernel: 64,
  95712. groundMirrorAmount: 1,
  95713. groundMirrorFresnelWeight: 1,
  95714. groundMirrorFallOffDistance: 0,
  95715. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  95716. groundYBias: 0.00001,
  95717. createSkybox: true,
  95718. skyboxSize: 20,
  95719. skyboxTexture: this._skyboxTextureCDNUrl,
  95720. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  95721. backgroundYRotation: 0,
  95722. sizeAuto: true,
  95723. rootPosition: BABYLON.Vector3.Zero(),
  95724. setupImageProcessing: true,
  95725. environmentTexture: this._environmentTextureCDNUrl,
  95726. cameraExposure: 0.8,
  95727. cameraContrast: 1.2,
  95728. toneMappingEnabled: true,
  95729. };
  95730. };
  95731. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  95732. /**
  95733. * Gets the root mesh created by the helper.
  95734. */
  95735. get: function () {
  95736. return this._rootMesh;
  95737. },
  95738. enumerable: true,
  95739. configurable: true
  95740. });
  95741. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  95742. /**
  95743. * Gets the skybox created by the helper.
  95744. */
  95745. get: function () {
  95746. return this._skybox;
  95747. },
  95748. enumerable: true,
  95749. configurable: true
  95750. });
  95751. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  95752. /**
  95753. * Gets the skybox texture created by the helper.
  95754. */
  95755. get: function () {
  95756. return this._skyboxTexture;
  95757. },
  95758. enumerable: true,
  95759. configurable: true
  95760. });
  95761. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  95762. /**
  95763. * Gets the skybox material created by the helper.
  95764. */
  95765. get: function () {
  95766. return this._skyboxMaterial;
  95767. },
  95768. enumerable: true,
  95769. configurable: true
  95770. });
  95771. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  95772. /**
  95773. * Gets the ground mesh created by the helper.
  95774. */
  95775. get: function () {
  95776. return this._ground;
  95777. },
  95778. enumerable: true,
  95779. configurable: true
  95780. });
  95781. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  95782. /**
  95783. * Gets the ground texture created by the helper.
  95784. */
  95785. get: function () {
  95786. return this._groundTexture;
  95787. },
  95788. enumerable: true,
  95789. configurable: true
  95790. });
  95791. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  95792. /**
  95793. * Gets the ground mirror created by the helper.
  95794. */
  95795. get: function () {
  95796. return this._groundMirror;
  95797. },
  95798. enumerable: true,
  95799. configurable: true
  95800. });
  95801. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  95802. /**
  95803. * Gets the ground mirror render list to helps pushing the meshes
  95804. * you wish in the ground reflection.
  95805. */
  95806. get: function () {
  95807. if (this._groundMirror) {
  95808. return this._groundMirror.renderList;
  95809. }
  95810. return null;
  95811. },
  95812. enumerable: true,
  95813. configurable: true
  95814. });
  95815. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  95816. /**
  95817. * Gets the ground material created by the helper.
  95818. */
  95819. get: function () {
  95820. return this._groundMaterial;
  95821. },
  95822. enumerable: true,
  95823. configurable: true
  95824. });
  95825. /**
  95826. * Updates the background according to the new options
  95827. * @param options
  95828. */
  95829. EnvironmentHelper.prototype.updateOptions = function (options) {
  95830. var newOptions = __assign({}, this._options, options);
  95831. if (this._ground && !newOptions.createGround) {
  95832. this._ground.dispose();
  95833. this._ground = null;
  95834. }
  95835. if (this._groundMaterial && !newOptions.createGround) {
  95836. this._groundMaterial.dispose();
  95837. this._groundMaterial = null;
  95838. }
  95839. if (this._groundTexture) {
  95840. if (this._options.groundTexture != newOptions.groundTexture) {
  95841. this._groundTexture.dispose();
  95842. this._groundTexture = null;
  95843. }
  95844. }
  95845. if (this._skybox && !newOptions.createSkybox) {
  95846. this._skybox.dispose();
  95847. this._skybox = null;
  95848. }
  95849. if (this._skyboxMaterial && !newOptions.createSkybox) {
  95850. this._skyboxMaterial.dispose();
  95851. this._skyboxMaterial = null;
  95852. }
  95853. if (this._skyboxTexture) {
  95854. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  95855. this._skyboxTexture.dispose();
  95856. this._skyboxTexture = null;
  95857. }
  95858. }
  95859. if (this._groundMirror && !newOptions.enableGroundMirror) {
  95860. this._groundMirror.dispose();
  95861. this._groundMirror = null;
  95862. }
  95863. if (this._scene.environmentTexture) {
  95864. if (this._options.environmentTexture != newOptions.environmentTexture) {
  95865. this._scene.environmentTexture.dispose();
  95866. }
  95867. }
  95868. this._options = newOptions;
  95869. this._setupBackground();
  95870. this._setupImageProcessing();
  95871. };
  95872. /**
  95873. * Sets the primary color of all the available elements.
  95874. * @param color the main color to affect to the ground and the background
  95875. * @param perceptual Specifies wether the chosen color has been set as intented to be seen e.g. in gamma space not accounting for exposure and tone mapping
  95876. */
  95877. EnvironmentHelper.prototype.setMainColor = function (color, perceptual) {
  95878. if (perceptual === void 0) { perceptual = false; }
  95879. if (this.groundMaterial) {
  95880. if (perceptual) {
  95881. this.groundMaterial.perceptualColor = color;
  95882. }
  95883. else {
  95884. this.groundMaterial.primaryColor = color;
  95885. }
  95886. }
  95887. if (this.skyboxMaterial) {
  95888. if (perceptual) {
  95889. this.skyboxMaterial.perceptualColor = color;
  95890. }
  95891. else {
  95892. this.skyboxMaterial.primaryColor = color;
  95893. }
  95894. }
  95895. if (this.groundMirror) {
  95896. if (perceptual && this.groundMaterial) {
  95897. this.groundMirror.clearColor = new BABYLON.Color4(this.groundMaterial.primaryColor.r, this.groundMaterial.primaryColor.g, this.groundMaterial.primaryColor.b, 1.0);
  95898. }
  95899. else {
  95900. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  95901. }
  95902. }
  95903. };
  95904. /**
  95905. * Setup the image processing according to the specified options.
  95906. */
  95907. EnvironmentHelper.prototype._setupImageProcessing = function () {
  95908. if (this._options.setupImageProcessing) {
  95909. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  95910. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  95911. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  95912. this._setupEnvironmentTexture();
  95913. }
  95914. };
  95915. /**
  95916. * Setup the environment texture according to the specified options.
  95917. */
  95918. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  95919. if (this._scene.environmentTexture) {
  95920. return;
  95921. }
  95922. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  95923. this._scene.environmentTexture = this._options.environmentTexture;
  95924. return;
  95925. }
  95926. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  95927. this._scene.environmentTexture = environmentTexture;
  95928. };
  95929. /**
  95930. * Setup the background according to the specified options.
  95931. */
  95932. EnvironmentHelper.prototype._setupBackground = function () {
  95933. if (!this._rootMesh) {
  95934. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  95935. }
  95936. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  95937. var sceneSize = this._getSceneSize();
  95938. if (this._options.createGround) {
  95939. this._setupGround(sceneSize);
  95940. this._setupGroundMaterial();
  95941. this._setupGroundDiffuseTexture();
  95942. if (this._options.enableGroundMirror) {
  95943. this._setupGroundMirrorTexture(sceneSize);
  95944. }
  95945. this._setupMirrorInGroundMaterial();
  95946. }
  95947. if (this._options.createSkybox) {
  95948. this._setupSkybox(sceneSize);
  95949. this._setupSkyboxMaterial();
  95950. this._setupSkyboxReflectionTexture();
  95951. }
  95952. this._rootMesh.position.x = sceneSize.rootPosition.x;
  95953. this._rootMesh.position.z = sceneSize.rootPosition.z;
  95954. this._rootMesh.position.y = sceneSize.rootPosition.y;
  95955. };
  95956. /**
  95957. * Get the scene sizes according to the setup.
  95958. */
  95959. EnvironmentHelper.prototype._getSceneSize = function () {
  95960. var _this = this;
  95961. var groundSize = this._options.groundSize;
  95962. var skyboxSize = this._options.skyboxSize;
  95963. var rootPosition = this._options.rootPosition;
  95964. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  95965. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95966. }
  95967. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  95968. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  95969. });
  95970. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  95971. if (this._options.sizeAuto) {
  95972. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  95973. this._scene.activeCamera.upperRadiusLimit) {
  95974. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  95975. skyboxSize = groundSize;
  95976. }
  95977. var sceneDiagonalLenght = sceneDiagonal.length();
  95978. if (sceneDiagonalLenght > groundSize) {
  95979. groundSize = sceneDiagonalLenght * 2;
  95980. skyboxSize = groundSize;
  95981. }
  95982. // 10 % bigger.
  95983. groundSize *= 1.1;
  95984. skyboxSize *= 1.5;
  95985. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  95986. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  95987. }
  95988. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95989. };
  95990. /**
  95991. * Setup the ground according to the specified options.
  95992. */
  95993. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  95994. var _this = this;
  95995. if (!this._ground) {
  95996. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  95997. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  95998. this._ground.parent = this._rootMesh;
  95999. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  96000. }
  96001. this._ground.receiveShadows = this._options.enableGroundShadow;
  96002. };
  96003. /**
  96004. * Setup the ground material according to the specified options.
  96005. */
  96006. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  96007. if (!this._groundMaterial) {
  96008. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  96009. }
  96010. this._groundMaterial.alpha = this._options.groundOpacity;
  96011. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  96012. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  96013. this._groundMaterial.primaryColor = this._options.groundColor;
  96014. this._groundMaterial.useRGBColor = false;
  96015. this._groundMaterial.enableNoise = true;
  96016. if (this._ground) {
  96017. this._ground.material = this._groundMaterial;
  96018. }
  96019. };
  96020. /**
  96021. * Setup the ground diffuse texture according to the specified options.
  96022. */
  96023. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  96024. if (!this._groundMaterial) {
  96025. return;
  96026. }
  96027. if (this._groundTexture) {
  96028. return;
  96029. }
  96030. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  96031. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  96032. return;
  96033. }
  96034. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96035. diffuseTexture.gammaSpace = false;
  96036. diffuseTexture.hasAlpha = true;
  96037. this._groundMaterial.diffuseTexture = diffuseTexture;
  96038. };
  96039. /**
  96040. * Setup the ground mirror texture according to the specified options.
  96041. */
  96042. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  96043. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96044. if (!this._groundMirror) {
  96045. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  96046. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  96047. this._groundMirror.anisotropicFilteringLevel = 1;
  96048. this._groundMirror.wrapU = wrapping;
  96049. this._groundMirror.wrapV = wrapping;
  96050. this._groundMirror.gammaSpace = false;
  96051. if (this._groundMirror.renderList) {
  96052. for (var i = 0; i < this._scene.meshes.length; i++) {
  96053. var mesh = this._scene.meshes[i];
  96054. if (mesh !== this._ground &&
  96055. mesh !== this._skybox &&
  96056. mesh !== this._rootMesh) {
  96057. this._groundMirror.renderList.push(mesh);
  96058. }
  96059. }
  96060. }
  96061. }
  96062. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  96063. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  96064. };
  96065. /**
  96066. * Setup the ground to receive the mirror texture.
  96067. */
  96068. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  96069. if (this._groundMaterial) {
  96070. this._groundMaterial.reflectionTexture = this._groundMirror;
  96071. this._groundMaterial.reflectionFresnel = true;
  96072. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  96073. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  96074. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  96075. }
  96076. };
  96077. /**
  96078. * Setup the skybox according to the specified options.
  96079. */
  96080. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  96081. var _this = this;
  96082. if (!this._skybox) {
  96083. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  96084. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  96085. }
  96086. this._skybox.parent = this._rootMesh;
  96087. };
  96088. /**
  96089. * Setup the skybox material according to the specified options.
  96090. */
  96091. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  96092. if (!this._skybox) {
  96093. return;
  96094. }
  96095. if (!this._skyboxMaterial) {
  96096. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  96097. }
  96098. this._skyboxMaterial.useRGBColor = false;
  96099. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  96100. this._skyboxMaterial.enableNoise = true;
  96101. this._skybox.material = this._skyboxMaterial;
  96102. };
  96103. /**
  96104. * Setup the skybox reflection texture according to the specified options.
  96105. */
  96106. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  96107. if (!this._skyboxMaterial) {
  96108. return;
  96109. }
  96110. if (this._skyboxTexture) {
  96111. return;
  96112. }
  96113. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  96114. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  96115. return;
  96116. }
  96117. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96118. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  96119. this._skyboxTexture.gammaSpace = false;
  96120. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  96121. };
  96122. /**
  96123. * Dispose all the elements created by the Helper.
  96124. */
  96125. EnvironmentHelper.prototype.dispose = function () {
  96126. if (this._groundMaterial) {
  96127. this._groundMaterial.dispose(true, true);
  96128. }
  96129. if (this._skyboxMaterial) {
  96130. this._skyboxMaterial.dispose(true, true);
  96131. }
  96132. this._rootMesh.dispose(false);
  96133. };
  96134. /**
  96135. * Default ground texture URL.
  96136. */
  96137. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  96138. /**
  96139. * Default skybox texture URL.
  96140. */
  96141. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  96142. /**
  96143. * Default environment texture URL.
  96144. */
  96145. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  96146. return EnvironmentHelper;
  96147. }());
  96148. BABYLON.EnvironmentHelper = EnvironmentHelper;
  96149. })(BABYLON || (BABYLON = {}));
  96150. //# sourceMappingURL=babylon.environmentHelper.js.map
  96151. "use strict";
  96152. var BABYLON;
  96153. (function (BABYLON) {
  96154. /**
  96155. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  96156. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  96157. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  96158. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  96159. */
  96160. var VideoDome = /** @class */ (function (_super) {
  96161. __extends(VideoDome, _super);
  96162. /**
  96163. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  96164. * @param name Element's name, child elements will append suffixes for their own names.
  96165. * @param urlsOrVideo
  96166. * @param options An object containing optional or exposed sub element properties:
  96167. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  96168. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  96169. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  96170. * @param options **loop=true** Automatically loop video on end.
  96171. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  96172. */
  96173. function VideoDome(name, urlsOrVideo, options, scene) {
  96174. var _this = _super.call(this, name, scene) || this;
  96175. // set defaults and manage values
  96176. name = name || "videoDome";
  96177. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  96178. options.clickToPlay = Boolean(options.clickToPlay);
  96179. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  96180. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  96181. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  96182. // create
  96183. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  96184. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  96185. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  96186. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  96187. flat: false,
  96188. radius: options.size,
  96189. subdivisions: options.resolution,
  96190. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  96191. }, scene);
  96192. // configure material
  96193. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  96194. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  96195. material.reflectionTexture = _this._videoTexture;
  96196. material.useEquirectangularFOV = true;
  96197. material.fovMultiplier = 1.0;
  96198. // configure mesh
  96199. _this._mesh.material = material;
  96200. _this._mesh.parent = _this;
  96201. // optional configuration
  96202. if (options.clickToPlay) {
  96203. scene.onPointerUp = function () {
  96204. _this._videoTexture.video.play();
  96205. };
  96206. }
  96207. return _this;
  96208. }
  96209. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  96210. /**
  96211. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96212. * Also see the options.resolution property.
  96213. */
  96214. get: function () {
  96215. return this._material.fovMultiplier;
  96216. },
  96217. set: function (value) {
  96218. this._material.fovMultiplier = value;
  96219. },
  96220. enumerable: true,
  96221. configurable: true
  96222. });
  96223. /**
  96224. * Releases resources associated with this node.
  96225. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  96226. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  96227. */
  96228. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  96229. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  96230. this._videoTexture.dispose();
  96231. this._mesh.dispose();
  96232. this._material.dispose();
  96233. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  96234. };
  96235. return VideoDome;
  96236. }(BABYLON.Node));
  96237. BABYLON.VideoDome = VideoDome;
  96238. })(BABYLON || (BABYLON = {}));
  96239. //# sourceMappingURL=babylon.videoDome.js.map
  96240. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(GEOMETRYAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#ifdef GEOMETRYAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  96241. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  96242. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  96243. globalObject["BABYLON"] = BABYLON;
  96244. //backwards compatibility
  96245. if(typeof earcut !== 'undefined') {
  96246. globalObject["Earcut"] = {
  96247. earcut: earcut
  96248. };
  96249. }
  96250. return BABYLON;
  96251. });
  96252. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  96253. /***/ }),
  96254. /* 1 */
  96255. /***/ (function(module, exports, __webpack_require__) {
  96256. "use strict";
  96257. Object.defineProperty(exports, "__esModule", { value: true });
  96258. var babylonjs_1 = __webpack_require__(0);
  96259. var helper_1 = __webpack_require__(3);
  96260. /**
  96261. * This is a simple HTML mapper.
  96262. * This mapper parses a single HTML element and returns the configuration from its attributes.
  96263. * it parses numbers and boolean values to the corresponding variable types.
  96264. * The following HTML element:
  96265. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  96266. *
  96267. * {
  96268. * test: 1, //a number!
  96269. * randomFlag: boolean, //camelCase and boolean
  96270. * a: {
  96271. * string: {
  96272. * object: "test" //dot-separated object levels
  96273. * }
  96274. * }
  96275. * }
  96276. */
  96277. var HTMLMapper = /** @class */ (function () {
  96278. function HTMLMapper() {
  96279. }
  96280. /**
  96281. * Map a specific element and get configuration from it
  96282. * @param element the HTML element to analyze.
  96283. */
  96284. HTMLMapper.prototype.map = function (element) {
  96285. var config = {};
  96286. var _loop_1 = function (attrIdx) {
  96287. var attr = element.attributes.item(attrIdx);
  96288. // map "object.property" to the right configuration place.
  96289. var split = attr.nodeName.split('.');
  96290. split.reduce(function (currentConfig, key, idx) {
  96291. //convert html-style to json-style
  96292. var camelKey = helper_1.kebabToCamel(key);
  96293. if (idx === split.length - 1) {
  96294. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  96295. if (val === "true") {
  96296. val = true;
  96297. }
  96298. else if (val === "false") {
  96299. val = false;
  96300. }
  96301. else {
  96302. var isnum = /^\d+$/.test(val);
  96303. if (isnum) {
  96304. var number = parseFloat(val);
  96305. if (!isNaN(number)) {
  96306. val = number;
  96307. }
  96308. }
  96309. }
  96310. currentConfig[camelKey] = val;
  96311. }
  96312. else {
  96313. currentConfig[camelKey] = currentConfig[camelKey] || {};
  96314. }
  96315. return currentConfig[camelKey];
  96316. }, config);
  96317. };
  96318. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  96319. _loop_1(attrIdx);
  96320. }
  96321. return config;
  96322. };
  96323. return HTMLMapper;
  96324. }());
  96325. /**
  96326. * A simple string-to-JSON mapper.
  96327. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  96328. */
  96329. var JSONMapper = /** @class */ (function () {
  96330. function JSONMapper() {
  96331. }
  96332. JSONMapper.prototype.map = function (rawSource) {
  96333. return JSON.parse(rawSource);
  96334. };
  96335. return JSONMapper;
  96336. }());
  96337. /**
  96338. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  96339. * DOM elements and attributes.
  96340. */
  96341. var DOMMapper = /** @class */ (function () {
  96342. function DOMMapper() {
  96343. }
  96344. /**
  96345. * The mapping function that will convert HTML data to a viewer configuration object
  96346. * @param baseElement the baseElement from which to start traversing
  96347. * @returns a ViewerCOnfiguration object from the provided HTML Element
  96348. */
  96349. DOMMapper.prototype.map = function (baseElement) {
  96350. var htmlMapper = new HTMLMapper();
  96351. var config = htmlMapper.map(baseElement);
  96352. var traverseChildren = function (element, partConfig) {
  96353. var children = element.children;
  96354. if (children.length) {
  96355. for (var i = 0; i < children.length; ++i) {
  96356. var item = children.item(i);
  96357. // use the HTML Mapper to read configuration from a single element
  96358. var configMapped = htmlMapper.map(item);
  96359. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  96360. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  96361. partConfig[key] = [];
  96362. }
  96363. else {
  96364. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  96365. partConfig.push(configMapped);
  96366. }
  96367. else if (partConfig[key]) {
  96368. //exists already! probably an array
  96369. element.setAttribute('array', 'true');
  96370. var oldItem = partConfig[key];
  96371. partConfig = [oldItem, configMapped];
  96372. }
  96373. else {
  96374. partConfig[key] = configMapped;
  96375. }
  96376. }
  96377. traverseChildren(item, partConfig[key] || configMapped);
  96378. }
  96379. }
  96380. return partConfig;
  96381. };
  96382. traverseChildren(baseElement, config);
  96383. return config;
  96384. };
  96385. return DOMMapper;
  96386. }());
  96387. /**
  96388. * The MapperManager manages the different implemented mappers.
  96389. * It allows the user to register new mappers as well and use them to parse their own configuration data
  96390. */
  96391. var MapperManager = /** @class */ (function () {
  96392. function MapperManager() {
  96393. this._mappers = {
  96394. "html": new HTMLMapper(),
  96395. "json": new JSONMapper(),
  96396. "dom": new DOMMapper()
  96397. };
  96398. }
  96399. /**
  96400. * Get a specific configuration mapper.
  96401. *
  96402. * @param type the name of the mapper to load
  96403. */
  96404. MapperManager.prototype.getMapper = function (type) {
  96405. if (!this._mappers[type]) {
  96406. babylonjs_1.Tools.Error("No mapper defined for " + type);
  96407. }
  96408. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  96409. };
  96410. /**
  96411. * Use this functio to register your own configuration mapper.
  96412. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  96413. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  96414. * @param mapper The implemented mapper
  96415. */
  96416. MapperManager.prototype.registerMapper = function (type, mapper) {
  96417. this._mappers[type] = mapper;
  96418. };
  96419. /**
  96420. * Dispose the mapper manager and all of its mappers.
  96421. */
  96422. MapperManager.prototype.dispose = function () {
  96423. this._mappers = {};
  96424. };
  96425. /**
  96426. * The default mapper is the JSON mapper.
  96427. */
  96428. MapperManager.DefaultMapper = 'json';
  96429. return MapperManager;
  96430. }());
  96431. exports.MapperManager = MapperManager;
  96432. /**
  96433. * mapperManager is a singleton of the type MapperManager.
  96434. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  96435. * or indirectly with using BabylonViewer.disposeAll()
  96436. */
  96437. exports.mapperManager = new MapperManager();
  96438. /***/ }),
  96439. /* 2 */
  96440. /***/ (function(module, exports, __webpack_require__) {
  96441. (function (global, factory) {
  96442. true ? module.exports = factory() :
  96443. typeof define === 'function' && define.amd ? define(factory) :
  96444. (global.deepmerge = factory());
  96445. }(this, (function () { 'use strict';
  96446. var isMergeableObject = function isMergeableObject(value) {
  96447. return isNonNullObject(value)
  96448. && !isSpecial(value)
  96449. };
  96450. function isNonNullObject(value) {
  96451. return !!value && typeof value === 'object'
  96452. }
  96453. function isSpecial(value) {
  96454. var stringValue = Object.prototype.toString.call(value);
  96455. return stringValue === '[object RegExp]'
  96456. || stringValue === '[object Date]'
  96457. || isReactElement(value)
  96458. }
  96459. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  96460. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  96461. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  96462. function isReactElement(value) {
  96463. return value.$$typeof === REACT_ELEMENT_TYPE
  96464. }
  96465. function emptyTarget(val) {
  96466. return Array.isArray(val) ? [] : {}
  96467. }
  96468. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  96469. var clone = !optionsArgument || optionsArgument.clone !== false;
  96470. return (clone && isMergeableObject(value))
  96471. ? deepmerge(emptyTarget(value), value, optionsArgument)
  96472. : value
  96473. }
  96474. function defaultArrayMerge(target, source, optionsArgument) {
  96475. return target.concat(source).map(function(element) {
  96476. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  96477. })
  96478. }
  96479. function mergeObject(target, source, optionsArgument) {
  96480. var destination = {};
  96481. if (isMergeableObject(target)) {
  96482. Object.keys(target).forEach(function(key) {
  96483. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  96484. });
  96485. }
  96486. Object.keys(source).forEach(function(key) {
  96487. if (!isMergeableObject(source[key]) || !target[key]) {
  96488. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  96489. } else {
  96490. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  96491. }
  96492. });
  96493. return destination
  96494. }
  96495. function deepmerge(target, source, optionsArgument) {
  96496. var sourceIsArray = Array.isArray(source);
  96497. var targetIsArray = Array.isArray(target);
  96498. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  96499. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  96500. if (!sourceAndTargetTypesMatch) {
  96501. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  96502. } else if (sourceIsArray) {
  96503. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  96504. return arrayMerge(target, source, optionsArgument)
  96505. } else {
  96506. return mergeObject(target, source, optionsArgument)
  96507. }
  96508. }
  96509. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  96510. if (!Array.isArray(array)) {
  96511. throw new Error('first argument should be an array')
  96512. }
  96513. return array.reduce(function(prev, next) {
  96514. return deepmerge(prev, next, optionsArgument)
  96515. }, {})
  96516. };
  96517. var deepmerge_1 = deepmerge;
  96518. return deepmerge_1;
  96519. })));
  96520. /***/ }),
  96521. /* 3 */
  96522. /***/ (function(module, exports, __webpack_require__) {
  96523. "use strict";
  96524. Object.defineProperty(exports, "__esModule", { value: true });
  96525. /**
  96526. * Is the provided string a URL?
  96527. *
  96528. * @param urlToCheck the url to inspect
  96529. */
  96530. function isUrl(urlToCheck) {
  96531. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  96532. return true;
  96533. }
  96534. return false;
  96535. }
  96536. exports.isUrl = isUrl;
  96537. /**
  96538. * Convert a string from kebab-case to camelCase
  96539. * @param s string to convert
  96540. */
  96541. function kebabToCamel(s) {
  96542. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  96543. }
  96544. exports.kebabToCamel = kebabToCamel;
  96545. //https://gist.github.com/youssman/745578062609e8acac9f
  96546. /**
  96547. * Convert a string from camelCase to kebab-case
  96548. * @param str string to convert
  96549. */
  96550. function camelToKebab(str) {
  96551. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  96552. }
  96553. exports.camelToKebab = camelToKebab;
  96554. /***/ }),
  96555. /* 4 */
  96556. /***/ (function(module, exports, __webpack_require__) {
  96557. "use strict";
  96558. Object.defineProperty(exports, "__esModule", { value: true });
  96559. var babylonjs_1 = __webpack_require__(0);
  96560. /**
  96561. * The viewer manager is the container for all viewers currently registered on this page.
  96562. * It is possible to have more than one viewer on a single page.
  96563. */
  96564. var ViewerManager = /** @class */ (function () {
  96565. function ViewerManager() {
  96566. this._viewers = {};
  96567. this.onViewerAddedObservable = new babylonjs_1.Observable();
  96568. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  96569. }
  96570. /**
  96571. * Adding a new viewer to the viewer manager and start tracking it.
  96572. * @param viewer the viewer to add
  96573. */
  96574. ViewerManager.prototype.addViewer = function (viewer) {
  96575. this._viewers[viewer.getBaseId()] = viewer;
  96576. this._onViewerAdded(viewer);
  96577. };
  96578. /**
  96579. * remove a viewer from the viewer manager
  96580. * @param viewer the viewer to remove
  96581. */
  96582. ViewerManager.prototype.removeViewer = function (viewer) {
  96583. var id = viewer.getBaseId();
  96584. delete this._viewers[id];
  96585. this.onViewerRemovedObservable.notifyObservers(id);
  96586. };
  96587. /**
  96588. * 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)
  96589. * @param id the id of the HTMl element (or the viewer's, if none provided)
  96590. */
  96591. ViewerManager.prototype.getViewerById = function (id) {
  96592. return this._viewers[id];
  96593. };
  96594. /**
  96595. * Get a viewer using a container element
  96596. * @param element the HTML element to search viewers associated with
  96597. */
  96598. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  96599. for (var id in this._viewers) {
  96600. if (this._viewers[id].containerElement === element) {
  96601. return this.getViewerById(id);
  96602. }
  96603. }
  96604. };
  96605. /**
  96606. * Get a promise that will fullfil when this viewer was initialized.
  96607. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  96608. * you will get the viewer after everything was already configured.
  96609. * @param id the viewer id to find
  96610. */
  96611. ViewerManager.prototype.getViewerPromiseById = function (id) {
  96612. var _this = this;
  96613. return new Promise(function (resolve, reject) {
  96614. var localViewer = _this.getViewerById(id);
  96615. if (localViewer) {
  96616. return resolve(localViewer);
  96617. }
  96618. var viewerFunction = function (viewer) {
  96619. if (viewer.getBaseId() === id) {
  96620. resolve(viewer);
  96621. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  96622. }
  96623. };
  96624. _this.onViewerAddedObservable.add(viewerFunction);
  96625. });
  96626. };
  96627. ViewerManager.prototype._onViewerAdded = function (viewer) {
  96628. this.onViewerAdded && this.onViewerAdded(viewer);
  96629. this.onViewerAddedObservable.notifyObservers(viewer);
  96630. };
  96631. /**
  96632. * dispose the manager and all of its associated viewers
  96633. */
  96634. ViewerManager.prototype.dispose = function () {
  96635. for (var id in this._viewers) {
  96636. this._viewers[id].dispose();
  96637. }
  96638. };
  96639. return ViewerManager;
  96640. }());
  96641. exports.ViewerManager = ViewerManager;
  96642. exports.viewerManager = new ViewerManager();
  96643. /***/ }),
  96644. /* 5 */
  96645. /***/ (function(module, exports, __webpack_require__) {
  96646. "use strict";
  96647. var __extends = (this && this.__extends) || (function () {
  96648. var extendStatics = Object.setPrototypeOf ||
  96649. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  96650. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  96651. return function (d, b) {
  96652. extendStatics(d, b);
  96653. function __() { this.constructor = d; }
  96654. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  96655. };
  96656. })();
  96657. Object.defineProperty(exports, "__esModule", { value: true });
  96658. var viewer_1 = __webpack_require__(6);
  96659. var babylonjs_1 = __webpack_require__(0);
  96660. /**
  96661. * The Default viewer is the default implementation of the AbstractViewer.
  96662. * It uses the templating system to render a new canvas and controls.
  96663. */
  96664. var DefaultViewer = /** @class */ (function (_super) {
  96665. __extends(DefaultViewer, _super);
  96666. /**
  96667. * Create a new default viewer
  96668. * @param containerElement the element in which the templates will be rendered
  96669. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  96670. */
  96671. function DefaultViewer(containerElement, initialConfiguration) {
  96672. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  96673. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  96674. _this.containerElement = containerElement;
  96675. _this._onModelLoaded = function (model) {
  96676. _this._configureTemplate(model);
  96677. // with a short timeout, making sure everything is there already.
  96678. var hideLoadingDelay = 500;
  96679. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  96680. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  96681. }
  96682. setTimeout(function () {
  96683. _this.hideLoadingScreen();
  96684. }, hideLoadingDelay);
  96685. return;
  96686. };
  96687. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  96688. return _this;
  96689. }
  96690. /**
  96691. * Overriding the AbstractViewer's _initScene fcuntion
  96692. */
  96693. DefaultViewer.prototype._initScene = function () {
  96694. var _this = this;
  96695. return _super.prototype._initScene.call(this).then(function () {
  96696. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  96697. return _this.scene;
  96698. });
  96699. };
  96700. /**
  96701. * This will be executed when the templates initialize.
  96702. */
  96703. DefaultViewer.prototype._onTemplatesLoaded = function () {
  96704. var _this = this;
  96705. this.showLoadingScreen();
  96706. // navbar
  96707. this._initNavbar();
  96708. // close overlay button
  96709. var closeButton = document.getElementById('close-button');
  96710. if (closeButton) {
  96711. closeButton.addEventListener('pointerdown', function () {
  96712. _this.hideOverlayScreen();
  96713. });
  96714. }
  96715. return _super.prototype._onTemplatesLoaded.call(this);
  96716. };
  96717. DefaultViewer.prototype._initNavbar = function () {
  96718. var navbar = this.templateManager.getTemplate('navBar');
  96719. if (navbar) {
  96720. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  96721. var navbarShown_1 = true;
  96722. var timeoutCancel_1 /*: number*/;
  96723. var triggerNavbar = function (show, evt) {
  96724. if (show === void 0) { show = false; }
  96725. // only left-click on no-button.
  96726. if (!navbar || evt.button > 0)
  96727. return;
  96728. // clear timeout
  96729. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  96730. // if state is the same, do nothing
  96731. if (show === navbarShown_1)
  96732. return;
  96733. //showing? simply show it!
  96734. if (show) {
  96735. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  96736. navbarShown_1 = show;
  96737. }
  96738. else {
  96739. var visibilityTimeout = 2000;
  96740. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  96741. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  96742. }
  96743. // not showing? set timeout until it is removed.
  96744. timeoutCancel_1 = setTimeout(function () {
  96745. if (navbar) {
  96746. navbar.parent.style.bottom = '-' + navbarHeight_1;
  96747. }
  96748. navbarShown_1 = show;
  96749. }, visibilityTimeout);
  96750. }
  96751. };
  96752. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  96753. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  96754. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  96755. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  96756. // other events
  96757. var viewerTemplate = this.templateManager.getTemplate('viewer');
  96758. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  96759. // full screen
  96760. var triggerFullscren = function (eventData) {
  96761. if (viewerElement_1) {
  96762. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  96763. if (!fullscreenElement) {
  96764. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  96765. requestFullScreen.call(viewerElement_1);
  96766. }
  96767. else {
  96768. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  96769. exitFullscreen.call(document);
  96770. }
  96771. }
  96772. };
  96773. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  96774. }
  96775. };
  96776. /**
  96777. * Preparing the container element to present the viewer
  96778. */
  96779. DefaultViewer.prototype._prepareContainerElement = function () {
  96780. this.containerElement.style.position = 'relative';
  96781. this.containerElement.style.display = 'flex';
  96782. };
  96783. /**
  96784. * This function will configure the templates and update them after a model was loaded
  96785. * It is mainly responsible to changing the title and subtitle etc'.
  96786. * @param model the model to be used to configure the templates by
  96787. */
  96788. DefaultViewer.prototype._configureTemplate = function (model) {
  96789. var navbar = this.templateManager.getTemplate('navBar');
  96790. if (!navbar)
  96791. return;
  96792. var modelConfiguration = model.configuration;
  96793. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  96794. if (metadataContainer) {
  96795. if (modelConfiguration.title !== undefined) {
  96796. var element = metadataContainer.querySelector('span.model-title');
  96797. if (element) {
  96798. element.innerHTML = modelConfiguration.title;
  96799. }
  96800. }
  96801. if (modelConfiguration.subtitle !== undefined) {
  96802. var element = metadataContainer.querySelector('span.model-subtitle');
  96803. if (element) {
  96804. element.innerHTML = modelConfiguration.subtitle;
  96805. }
  96806. }
  96807. if (modelConfiguration.thumbnail !== undefined) {
  96808. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  96809. }
  96810. }
  96811. };
  96812. /**
  96813. * This will load a new model to the default viewer
  96814. * overriding the AbstractViewer's loadModel.
  96815. * The scene will automatically be cleared of the old models, if exist.
  96816. * @param model the configuration object (or URL) to load.
  96817. */
  96818. DefaultViewer.prototype.loadModel = function (model) {
  96819. var _this = this;
  96820. if (model === void 0) { model = this._configuration.model; }
  96821. this.showLoadingScreen();
  96822. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  96823. console.log(error);
  96824. _this.hideLoadingScreen();
  96825. _this.showOverlayScreen('error');
  96826. return Promise.reject(error);
  96827. });
  96828. };
  96829. /**
  96830. * Show the overlay and the defined sub-screen.
  96831. * Mainly used for help and errors
  96832. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  96833. */
  96834. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  96835. var _this = this;
  96836. var template = this.templateManager.getTemplate('overlay');
  96837. if (!template)
  96838. return Promise.resolve('Overlay template not found');
  96839. return template.show((function (template) {
  96840. var canvasRect = _this.containerElement.getBoundingClientRect();
  96841. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  96842. template.parent.style.display = 'flex';
  96843. template.parent.style.width = canvasRect.width + "px";
  96844. template.parent.style.height = canvasRect.height + "px";
  96845. template.parent.style.opacity = "1";
  96846. var subTemplate = _this.templateManager.getTemplate(subScreen);
  96847. if (!subTemplate) {
  96848. return Promise.reject(subScreen + ' template not found');
  96849. }
  96850. return subTemplate.show((function (template) {
  96851. template.parent.style.display = 'flex';
  96852. return Promise.resolve(template);
  96853. }));
  96854. }));
  96855. };
  96856. /**
  96857. * Hide the overlay screen.
  96858. */
  96859. DefaultViewer.prototype.hideOverlayScreen = function () {
  96860. var template = this.templateManager.getTemplate('overlay');
  96861. if (!template)
  96862. return Promise.resolve('Overlay template not found');
  96863. return template.hide((function (template) {
  96864. template.parent.style.opacity = "0";
  96865. var onTransitionEnd = function () {
  96866. template.parent.removeEventListener("transitionend", onTransitionEnd);
  96867. template.parent.style.display = 'none';
  96868. };
  96869. template.parent.addEventListener("transitionend", onTransitionEnd);
  96870. var overlays = template.parent.querySelectorAll('.overlay');
  96871. if (overlays) {
  96872. for (var i = 0; i < overlays.length; ++i) {
  96873. var htmlElement = overlays.item(i);
  96874. htmlElement.style.display = 'none';
  96875. }
  96876. }
  96877. return Promise.resolve(template);
  96878. }));
  96879. };
  96880. /**
  96881. * Show the loading screen.
  96882. * The loading screen can be configured using the configuration object
  96883. */
  96884. DefaultViewer.prototype.showLoadingScreen = function () {
  96885. var _this = this;
  96886. var template = this.templateManager.getTemplate('loadingScreen');
  96887. if (!template)
  96888. return Promise.resolve('Loading Screen template not found');
  96889. return template.show((function (template) {
  96890. var canvasRect = _this.containerElement.getBoundingClientRect();
  96891. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  96892. template.parent.style.display = 'flex';
  96893. template.parent.style.width = canvasRect.width + "px";
  96894. template.parent.style.height = canvasRect.height + "px";
  96895. template.parent.style.opacity = "1";
  96896. // from the configuration!!!
  96897. template.parent.style.backgroundColor = "black";
  96898. return Promise.resolve(template);
  96899. }));
  96900. };
  96901. /**
  96902. * Hide the loading screen
  96903. */
  96904. DefaultViewer.prototype.hideLoadingScreen = function () {
  96905. var template = this.templateManager.getTemplate('loadingScreen');
  96906. if (!template)
  96907. return Promise.resolve('Loading Screen template not found');
  96908. return template.hide((function (template) {
  96909. template.parent.style.opacity = "0";
  96910. var onTransitionEnd = function () {
  96911. template.parent.removeEventListener("transitionend", onTransitionEnd);
  96912. template.parent.style.display = 'none';
  96913. };
  96914. template.parent.addEventListener("transitionend", onTransitionEnd);
  96915. return Promise.resolve(template);
  96916. }));
  96917. };
  96918. /**
  96919. * An extension of the light configuration of the abstract viewer.
  96920. * @param lightsConfiguration the light configuration to use
  96921. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  96922. */
  96923. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  96924. var _this = this;
  96925. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  96926. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  96927. // labs feature - flashlight
  96928. if (this._configuration.lab && this._configuration.lab.flashlight) {
  96929. var pointerPosition = babylonjs_1.Vector3.Zero();
  96930. var lightTarget_1;
  96931. var angle = 0.5;
  96932. var exponent = Math.PI / 2;
  96933. if (typeof this._configuration.lab.flashlight === "object") {
  96934. exponent = this._configuration.lab.flashlight.exponent || exponent;
  96935. angle = this._configuration.lab.flashlight.angle || angle;
  96936. }
  96937. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  96938. if (typeof this._configuration.lab.flashlight === "object") {
  96939. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  96940. if (this._configuration.lab.flashlight.diffuse) {
  96941. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  96942. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  96943. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  96944. }
  96945. if (this._configuration.lab.flashlight.specular) {
  96946. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  96947. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  96948. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  96949. }
  96950. }
  96951. this.scene.constantlyUpdateMeshUnderPointer = true;
  96952. this.scene.onPointerObservable.add(function (eventData, eventState) {
  96953. if (eventData.type === 4 && eventData.pickInfo) {
  96954. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  96955. }
  96956. else {
  96957. lightTarget_1 = undefined;
  96958. }
  96959. });
  96960. var updateFlashlightFunction = function () {
  96961. if (_this.camera && flashlight) {
  96962. flashlight.position.copyFrom(_this.camera.position);
  96963. if (lightTarget_1) {
  96964. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  96965. }
  96966. }
  96967. };
  96968. this.scene.registerBeforeRender(updateFlashlightFunction);
  96969. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  96970. }
  96971. };
  96972. return DefaultViewer;
  96973. }(viewer_1.AbstractViewer));
  96974. exports.DefaultViewer = DefaultViewer;
  96975. /***/ }),
  96976. /* 6 */
  96977. /***/ (function(module, exports, __webpack_require__) {
  96978. "use strict";
  96979. Object.defineProperty(exports, "__esModule", { value: true });
  96980. var viewerManager_1 = __webpack_require__(4);
  96981. var templateManager_1 = __webpack_require__(23);
  96982. var loader_1 = __webpack_require__(26);
  96983. var babylonjs_1 = __webpack_require__(0);
  96984. var deepmerge = __webpack_require__(2);
  96985. var modelLoader_1 = __webpack_require__(14);
  96986. /**
  96987. * The AbstractViewr is the center of Babylon's viewer.
  96988. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  96989. */
  96990. var AbstractViewer = /** @class */ (function () {
  96991. function AbstractViewer(containerElement, initialConfiguration) {
  96992. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  96993. var _this = this;
  96994. this.containerElement = containerElement;
  96995. /**
  96996. * is this viewer disposed?
  96997. */
  96998. this._isDisposed = false;
  96999. /**
  97000. * The resize function that will be registered with the window object
  97001. */
  97002. this._resize = function () {
  97003. // Only resize if Canvas is in the DOM
  97004. if (!_this.isCanvasInDOM()) {
  97005. return;
  97006. }
  97007. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  97008. return;
  97009. }
  97010. _this.engine.resize();
  97011. };
  97012. /**
  97013. * render loop that will be executed by the engine
  97014. */
  97015. this._render = function () {
  97016. _this.scene && _this.scene.activeCamera && _this.scene.render();
  97017. };
  97018. // if exists, use the container id. otherwise, generate a random string.
  97019. if (containerElement.id) {
  97020. this.baseId = containerElement.id;
  97021. }
  97022. else {
  97023. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  97024. }
  97025. this.onSceneInitObservable = new babylonjs_1.Observable();
  97026. this.onEngineInitObservable = new babylonjs_1.Observable();
  97027. this.onModelLoadedObservable = new babylonjs_1.Observable();
  97028. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  97029. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  97030. this.onInitDoneObservable = new babylonjs_1.Observable();
  97031. this.onLoaderInitObservable = new babylonjs_1.Observable();
  97032. this._registeredOnBeforeRenderFunctions = [];
  97033. this.models = [];
  97034. this.modelLoader = new modelLoader_1.ModelLoader(this);
  97035. // add this viewer to the viewer manager
  97036. viewerManager_1.viewerManager.addViewer(this);
  97037. // create a new template manager. TODO - singleton?
  97038. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  97039. this._prepareContainerElement();
  97040. // extend the configuration
  97041. this._configurationLoader = new loader_1.ConfigurationLoader();
  97042. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  97043. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  97044. if (_this._configuration.observers) {
  97045. _this._configureObservers(_this._configuration.observers);
  97046. }
  97047. //this.updateConfiguration(configuration);
  97048. // initialize the templates
  97049. var templateConfiguration = _this._configuration.templates || {};
  97050. _this.templateManager.initTemplate(templateConfiguration);
  97051. // when done, execute onTemplatesLoaded()
  97052. _this.templateManager.onAllLoaded.add(function () {
  97053. var canvas = _this.templateManager.getCanvas();
  97054. if (canvas) {
  97055. _this._canvas = canvas;
  97056. }
  97057. _this._onTemplateLoaded();
  97058. });
  97059. });
  97060. }
  97061. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  97062. /**
  97063. * Returns a boolean representing HDR support
  97064. */
  97065. get: function () {
  97066. return this._hdrSupport;
  97067. },
  97068. enumerable: true,
  97069. configurable: true
  97070. });
  97071. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  97072. /**
  97073. * The (single) canvas of this viewer
  97074. */
  97075. get: function () {
  97076. return this._canvas;
  97077. },
  97078. enumerable: true,
  97079. configurable: true
  97080. });
  97081. /**
  97082. * get the baseId of this viewer
  97083. */
  97084. AbstractViewer.prototype.getBaseId = function () {
  97085. return this.baseId;
  97086. };
  97087. /**
  97088. * Do we have a canvas to render on, and is it a part of the scene
  97089. */
  97090. AbstractViewer.prototype.isCanvasInDOM = function () {
  97091. return !!this._canvas && !!this._canvas.parentElement;
  97092. };
  97093. /**
  97094. * Update the current viewer configuration with new values.
  97095. * Only provided information will be updated, old configuration values will be kept.
  97096. * If this.configuration was manually changed, you can trigger this function with no parameters,
  97097. * and the entire configuration will be updated.
  97098. * @param newConfiguration
  97099. */
  97100. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  97101. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  97102. // update this.configuration with the new data
  97103. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  97104. // update scene configuration
  97105. if (newConfiguration.scene) {
  97106. this._configureScene(newConfiguration.scene);
  97107. }
  97108. // optimizer
  97109. if (newConfiguration.optimizer) {
  97110. this._configureOptimizer(newConfiguration.optimizer);
  97111. }
  97112. // observers in configuration
  97113. if (newConfiguration.observers) {
  97114. this._configureObservers(newConfiguration.observers);
  97115. }
  97116. // configure model
  97117. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  97118. this._configureModel(newConfiguration.model);
  97119. }
  97120. // lights
  97121. if (newConfiguration.lights) {
  97122. this._configureLights(newConfiguration.lights);
  97123. }
  97124. // environment
  97125. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  97126. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  97127. }
  97128. // camera
  97129. if (newConfiguration.camera) {
  97130. this._configureCamera(newConfiguration.camera);
  97131. }
  97132. };
  97133. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  97134. if (!skyboxConifguration && !groundConfiguration) {
  97135. if (this.environmentHelper) {
  97136. this.environmentHelper.dispose();
  97137. delete this.environmentHelper;
  97138. }
  97139. ;
  97140. return Promise.resolve(this.scene);
  97141. }
  97142. var options = {
  97143. createGround: !!groundConfiguration,
  97144. createSkybox: !!skyboxConifguration,
  97145. setupImageProcessing: false // will be done at the scene level!
  97146. };
  97147. if (groundConfiguration) {
  97148. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  97149. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  97150. if (groundSize) {
  97151. options.groundSize = groundSize;
  97152. }
  97153. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  97154. if (groundConfig.shadowLevel !== undefined) {
  97155. options.groundShadowLevel = groundConfig.shadowLevel;
  97156. }
  97157. options.enableGroundMirror = !!groundConfig.mirror;
  97158. if (groundConfig.texture) {
  97159. options.groundTexture = groundConfig.texture;
  97160. }
  97161. if (groundConfig.color) {
  97162. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  97163. }
  97164. if (groundConfig.opacity !== undefined) {
  97165. options.groundOpacity = groundConfig.opacity;
  97166. }
  97167. if (groundConfig.mirror) {
  97168. options.enableGroundMirror = true;
  97169. // to prevent undefines
  97170. if (typeof groundConfig.mirror === "object") {
  97171. if (groundConfig.mirror.amount !== undefined)
  97172. options.groundMirrorAmount = groundConfig.mirror.amount;
  97173. if (groundConfig.mirror.sizeRatio !== undefined)
  97174. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  97175. if (groundConfig.mirror.blurKernel !== undefined)
  97176. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  97177. if (groundConfig.mirror.fresnelWeight !== undefined)
  97178. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  97179. if (groundConfig.mirror.fallOffDistance !== undefined)
  97180. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  97181. if (this._defaultPipelineTextureType !== undefined)
  97182. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  97183. }
  97184. }
  97185. }
  97186. var postInitSkyboxMaterial = false;
  97187. if (skyboxConifguration) {
  97188. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  97189. if (conf.material && conf.material.imageProcessingConfiguration) {
  97190. options.setupImageProcessing = false; // will be configured later manually.
  97191. }
  97192. var skyboxSize = conf.scale;
  97193. if (skyboxSize) {
  97194. options.skyboxSize = skyboxSize;
  97195. }
  97196. options.sizeAuto = !options.skyboxSize;
  97197. if (conf.color) {
  97198. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  97199. }
  97200. if (conf.cubeTexture && conf.cubeTexture.url) {
  97201. if (typeof conf.cubeTexture.url === "string") {
  97202. options.skyboxTexture = conf.cubeTexture.url;
  97203. }
  97204. else {
  97205. // init later!
  97206. postInitSkyboxMaterial = true;
  97207. }
  97208. }
  97209. if (conf.material && conf.material.imageProcessingConfiguration) {
  97210. postInitSkyboxMaterial = true;
  97211. }
  97212. }
  97213. options.setupImageProcessing = false; // TMP
  97214. if (!this.environmentHelper) {
  97215. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97216. }
  97217. else {
  97218. // there might be a new scene! we need to dispose.
  97219. // get the scene used by the envHelper
  97220. var scene = this.environmentHelper.rootMesh.getScene();
  97221. // is it a different scene? Oh no!
  97222. if (scene !== this.scene) {
  97223. this.environmentHelper.dispose();
  97224. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97225. }
  97226. else {
  97227. this.environmentHelper.updateOptions(options);
  97228. }
  97229. }
  97230. if (postInitSkyboxMaterial) {
  97231. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  97232. if (skyboxMaterial) {
  97233. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  97234. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  97235. }
  97236. }
  97237. }
  97238. };
  97239. /**
  97240. * internally configure the scene using the provided configuration.
  97241. * The scene will not be recreated, but just updated.
  97242. * @param sceneConfig the (new) scene configuration
  97243. */
  97244. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  97245. // sanity check!
  97246. if (!this.scene) {
  97247. return;
  97248. }
  97249. if (sceneConfig.debug) {
  97250. this.scene.debugLayer.show();
  97251. }
  97252. else {
  97253. if (this.scene.debugLayer.isVisible()) {
  97254. this.scene.debugLayer.hide();
  97255. }
  97256. }
  97257. if (sceneConfig.clearColor) {
  97258. var cc = sceneConfig.clearColor;
  97259. var oldcc = this.scene.clearColor;
  97260. if (cc.r !== undefined) {
  97261. oldcc.r = cc.r;
  97262. }
  97263. if (cc.g !== undefined) {
  97264. oldcc.g = cc.g;
  97265. }
  97266. if (cc.b !== undefined) {
  97267. oldcc.b = cc.b;
  97268. }
  97269. if (cc.a !== undefined) {
  97270. oldcc.a = cc.a;
  97271. }
  97272. }
  97273. // image processing configuration - optional.
  97274. if (sceneConfig.imageProcessingConfiguration) {
  97275. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  97276. }
  97277. if (sceneConfig.environmentTexture) {
  97278. if (this.scene.environmentTexture) {
  97279. this.scene.environmentTexture.dispose();
  97280. }
  97281. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  97282. this.scene.environmentTexture = environmentTexture;
  97283. }
  97284. if (sceneConfig.autoRotate) {
  97285. this.camera.useAutoRotationBehavior = true;
  97286. }
  97287. };
  97288. /**
  97289. * Configure the scene optimizer.
  97290. * The existing scene optimizer will be disposed and a new one will be created.
  97291. * @param optimizerConfig the (new) optimizer configuration
  97292. */
  97293. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  97294. if (typeof optimizerConfig === 'boolean') {
  97295. if (this.sceneOptimizer) {
  97296. this.sceneOptimizer.stop();
  97297. this.sceneOptimizer.dispose();
  97298. delete this.sceneOptimizer;
  97299. }
  97300. if (optimizerConfig) {
  97301. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  97302. this.sceneOptimizer.start();
  97303. }
  97304. }
  97305. else {
  97306. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  97307. // check for degradation
  97308. if (optimizerConfig.degradation) {
  97309. switch (optimizerConfig.degradation) {
  97310. case "low":
  97311. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  97312. break;
  97313. case "moderate":
  97314. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  97315. break;
  97316. case "hight":
  97317. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  97318. break;
  97319. }
  97320. }
  97321. if (this.sceneOptimizer) {
  97322. this.sceneOptimizer.stop();
  97323. this.sceneOptimizer.dispose();
  97324. }
  97325. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  97326. this.sceneOptimizer.start();
  97327. }
  97328. };
  97329. /**
  97330. * this is used to register native functions using the configuration object.
  97331. * This will configure the observers.
  97332. * @param observersConfiguration observers configuration
  97333. */
  97334. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  97335. if (observersConfiguration.onEngineInit) {
  97336. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  97337. }
  97338. else {
  97339. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  97340. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  97341. }
  97342. }
  97343. if (observersConfiguration.onSceneInit) {
  97344. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  97345. }
  97346. else {
  97347. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  97348. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  97349. }
  97350. }
  97351. if (observersConfiguration.onModelLoaded) {
  97352. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  97353. }
  97354. else {
  97355. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  97356. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  97357. }
  97358. }
  97359. };
  97360. /**
  97361. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  97362. * @param cameraConfig the new camera configuration
  97363. * @param model optionally use the model to configure the camera.
  97364. */
  97365. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  97366. var _this = this;
  97367. var focusMeshes = model ? model.meshes : this.scene.meshes;
  97368. if (!this.scene.activeCamera) {
  97369. this.scene.createDefaultCamera(true, true, true);
  97370. this.camera = this.scene.activeCamera;
  97371. }
  97372. if (cameraConfig.position) {
  97373. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  97374. }
  97375. if (cameraConfig.rotation) {
  97376. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  97377. }
  97378. this._extendClassWithConfig(this.camera, cameraConfig);
  97379. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  97380. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  97381. if (cameraConfig.behaviors) {
  97382. for (var name_1 in cameraConfig.behaviors) {
  97383. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  97384. }
  97385. }
  97386. ;
  97387. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  97388. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  97389. });
  97390. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97391. var sceneDiagonalLenght = sceneDiagonal.length();
  97392. if (isFinite(sceneDiagonalLenght))
  97393. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  97394. };
  97395. /**
  97396. * configure the lights.
  97397. *
  97398. * @param lightsConfiguration the (new) light(s) configuration
  97399. * @param model optionally use the model to configure the camera.
  97400. */
  97401. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  97402. var _this = this;
  97403. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  97404. var focusMeshes = model ? model.meshes : this.scene.meshes;
  97405. // sanity check!
  97406. if (!Object.keys(lightsConfiguration).length)
  97407. return;
  97408. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  97409. // compare to the global (!) configuration object and dispose unneeded:
  97410. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  97411. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  97412. lightsAvailable.forEach(function (lName) {
  97413. if (lightsToConfigure.indexOf(lName) === -1) {
  97414. _this.scene.getLightByName(lName).dispose();
  97415. }
  97416. });
  97417. }
  97418. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  97419. var lightConfig = { type: 0 };
  97420. if (typeof lightsConfiguration[name] === 'object') {
  97421. lightConfig = lightsConfiguration[name];
  97422. }
  97423. lightConfig.name = name;
  97424. var light;
  97425. // light is not already available
  97426. if (lightsAvailable.indexOf(name) === -1) {
  97427. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  97428. if (!constructor)
  97429. return;
  97430. light = constructor();
  97431. }
  97432. else {
  97433. // available? get it from the scene
  97434. light = _this.scene.getLightByName(name);
  97435. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  97436. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  97437. light.dispose();
  97438. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  97439. if (!constructor)
  97440. return;
  97441. light = constructor();
  97442. }
  97443. }
  97444. // if config set the light to false, dispose it.
  97445. if (lightsConfiguration[name] === false) {
  97446. light.dispose();
  97447. return;
  97448. }
  97449. //enabled
  97450. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  97451. light.setEnabled(enabled);
  97452. _this._extendClassWithConfig(light, lightConfig);
  97453. //position. Some lights don't support shadows
  97454. if (light instanceof babylonjs_1.ShadowLight) {
  97455. if (lightConfig.target) {
  97456. if (light.setDirectionToTarget) {
  97457. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  97458. light.setDirectionToTarget(target);
  97459. }
  97460. }
  97461. else if (lightConfig.direction) {
  97462. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  97463. light.direction = direction;
  97464. }
  97465. var shadowGenerator = light.getShadowGenerator();
  97466. if (lightConfig.shadowEnabled && _this._maxShadows) {
  97467. if (!shadowGenerator) {
  97468. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  97469. // TODO blur kernel definition
  97470. }
  97471. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  97472. // add the focues meshes to the shadow list
  97473. var shadownMap = shadowGenerator.getShadowMap();
  97474. if (!shadownMap)
  97475. return;
  97476. var renderList = shadownMap.renderList;
  97477. for (var index = 0; index < focusMeshes.length; index++) {
  97478. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  97479. renderList && renderList.push(focusMeshes[index]);
  97480. }
  97481. }
  97482. }
  97483. else if (shadowGenerator) {
  97484. shadowGenerator.dispose();
  97485. }
  97486. }
  97487. });
  97488. };
  97489. /**
  97490. * configure all models using the configuration.
  97491. * @param modelConfiguration the configuration to use to reconfigure the models
  97492. */
  97493. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  97494. this.models.forEach(function (model) {
  97495. model.updateConfiguration(modelConfiguration);
  97496. });
  97497. };
  97498. /**
  97499. * Dispoe the entire viewer including the scene and the engine
  97500. */
  97501. AbstractViewer.prototype.dispose = function () {
  97502. if (this._isDisposed) {
  97503. return;
  97504. }
  97505. window.removeEventListener('resize', this._resize);
  97506. if (this.sceneOptimizer) {
  97507. this.sceneOptimizer.stop();
  97508. this.sceneOptimizer.dispose();
  97509. }
  97510. if (this.environmentHelper) {
  97511. this.environmentHelper.dispose();
  97512. }
  97513. if (this._configurationLoader) {
  97514. this._configurationLoader.dispose();
  97515. }
  97516. //observers
  97517. this.onEngineInitObservable.clear();
  97518. delete this.onEngineInitObservable;
  97519. this.onInitDoneObservable.clear();
  97520. delete this.onInitDoneObservable;
  97521. this.onLoaderInitObservable.clear();
  97522. delete this.onLoaderInitObservable;
  97523. this.onModelLoadedObservable.clear();
  97524. delete this.onModelLoadedObservable;
  97525. this.onModelLoadErrorObservable.clear();
  97526. delete this.onModelLoadErrorObservable;
  97527. this.onModelLoadProgressObservable.clear();
  97528. delete this.onModelLoadProgressObservable;
  97529. this.onSceneInitObservable.clear();
  97530. delete this.onSceneInitObservable;
  97531. if (this.scene.activeCamera) {
  97532. this.scene.activeCamera.detachControl(this.canvas);
  97533. }
  97534. this.modelLoader.dispose();
  97535. this.models.forEach(function (model) {
  97536. model.dispose();
  97537. });
  97538. this.models.length = 0;
  97539. this.scene.dispose();
  97540. this.engine.dispose();
  97541. this.templateManager.dispose();
  97542. viewerManager_1.viewerManager.removeViewer(this);
  97543. this._isDisposed = true;
  97544. };
  97545. /**
  97546. * This function will execute when the HTML templates finished initializing.
  97547. * It should initialize the engine and continue execution.
  97548. *
  97549. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  97550. */
  97551. AbstractViewer.prototype._onTemplatesLoaded = function () {
  97552. return Promise.resolve(this);
  97553. };
  97554. /**
  97555. * This will force the creation of an engine and a scene.
  97556. * It will also load a model if preconfigured.
  97557. * But first - it will load the extendible onTemplateLoaded()!
  97558. */
  97559. AbstractViewer.prototype._onTemplateLoaded = function () {
  97560. var _this = this;
  97561. return this._onTemplatesLoaded().then(function () {
  97562. var autoLoadModel = _this._configuration.model;
  97563. return _this._initEngine().then(function (engine) {
  97564. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  97565. }).then(function () {
  97566. if (autoLoadModel) {
  97567. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  97568. }
  97569. else {
  97570. return _this.scene || _this._initScene();
  97571. }
  97572. }).then(function (scene) {
  97573. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  97574. }).then(function () {
  97575. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  97576. }).catch(function (e) {
  97577. babylonjs_1.Tools.Warn(e.toString());
  97578. return _this;
  97579. });
  97580. });
  97581. };
  97582. /**
  97583. * Initialize the engine. Retruns a promise in case async calls are needed.
  97584. *
  97585. * @protected
  97586. * @returns {Promise<Engine>}
  97587. * @memberof Viewer
  97588. */
  97589. AbstractViewer.prototype._initEngine = function () {
  97590. // init custom shaders
  97591. this._injectCustomShaders();
  97592. var canvasElement = this.templateManager.getCanvas();
  97593. if (!canvasElement) {
  97594. return Promise.reject('Canvas element not found!');
  97595. }
  97596. var config = this._configuration.engine || {};
  97597. // TDO enable further configuration
  97598. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  97599. // Disable manifest checking
  97600. babylonjs_1.Database.IDBStorageEnabled = false;
  97601. if (!config.disableResize) {
  97602. window.addEventListener('resize', this._resize);
  97603. }
  97604. this.engine.runRenderLoop(this._render);
  97605. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  97606. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  97607. this.engine.setHardwareScalingLevel(scale);
  97608. }
  97609. // set hardware limitations for scene initialization
  97610. this._handleHardwareLimitations();
  97611. return Promise.resolve(this.engine);
  97612. };
  97613. /**
  97614. * initialize the scene. Calling thsi function again will dispose the old scene, if exists.
  97615. */
  97616. AbstractViewer.prototype._initScene = function () {
  97617. // if the scen exists, dispose it.
  97618. if (this.scene) {
  97619. this.scene.dispose();
  97620. }
  97621. // create a new scene
  97622. this.scene = new babylonjs_1.Scene(this.engine);
  97623. // make sure there is a default camera and light.
  97624. this.scene.createDefaultLight(true);
  97625. if (this._configuration.scene) {
  97626. this._configureScene(this._configuration.scene);
  97627. // Scene optimizer
  97628. if (this._configuration.optimizer) {
  97629. this._configureOptimizer(this._configuration.optimizer);
  97630. }
  97631. }
  97632. return Promise.resolve(this.scene);
  97633. };
  97634. /**
  97635. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  97636. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  97637. *
  97638. * @param modelConfig model configuration to use when loading the model.
  97639. * @param clearScene should the scene be cleared before loading this model
  97640. * @returns a ViewerModel object that is not yet fully loaded.
  97641. */
  97642. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  97643. var _this = this;
  97644. if (clearScene === void 0) { clearScene = true; }
  97645. if (clearScene) {
  97646. this.models.forEach(function (m) { return m.dispose(); });
  97647. this.models.length = 0;
  97648. }
  97649. var model = this.modelLoader.load(modelConfig);
  97650. this.lastUsedLoader = model.loader;
  97651. model.onLoadErrorObservable.add(function (errorObject) {
  97652. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  97653. });
  97654. model.onLoadProgressObservable.add(function (progressEvent) {
  97655. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  97656. });
  97657. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  97658. model.onLoadedObservable.add(function () {
  97659. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  97660. .then(function () {
  97661. _this._configureLights(_this._configuration.lights);
  97662. if (_this._configuration.camera || !_this.scene.activeCamera) {
  97663. _this._configureCamera(_this._configuration.camera || {}, model);
  97664. }
  97665. return _this._initEnvironment(model);
  97666. }).then(function () {
  97667. _this._isLoading = false;
  97668. return model;
  97669. });
  97670. });
  97671. return model;
  97672. };
  97673. /**
  97674. * load a model using the provided configuration
  97675. *
  97676. * @param modelConfig the model configuration or URL to load.
  97677. * @param clearScene Should the scene be cleared before loading the model
  97678. * @returns a Promise the fulfills when the model finished loading successfully.
  97679. */
  97680. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  97681. var _this = this;
  97682. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  97683. if (clearScene === void 0) { clearScene = true; }
  97684. // no model was provided? Do nothing!
  97685. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  97686. if (!modelUrl) {
  97687. return Promise.reject("no model configuration found");
  97688. }
  97689. if (this._isLoading) {
  97690. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  97691. return Promise.reject("another model is curently being loaded.");
  97692. }
  97693. this._isLoading = true;
  97694. if ((typeof modelConfig === 'string')) {
  97695. if (this._configuration.model && typeof this._configuration.model === 'object') {
  97696. this._configuration.model.url = modelConfig;
  97697. }
  97698. }
  97699. else {
  97700. if (this._configuration.model) {
  97701. deepmerge(this._configuration.model, modelConfig);
  97702. }
  97703. else {
  97704. this._configuration.model = modelConfig;
  97705. }
  97706. }
  97707. return Promise.resolve(this.scene).then(function (scene) {
  97708. if (!scene)
  97709. return _this._initScene();
  97710. return scene;
  97711. }).then(function () {
  97712. return new Promise(function (resolve, reject) {
  97713. // at this point, configuration.model is an object, not a string
  97714. return _this.initModel(modelConfig, clearScene);
  97715. });
  97716. });
  97717. };
  97718. /**
  97719. * initialize the environment for a specific model.
  97720. * Per default it will use the viewer'S configuration.
  97721. * @param model the model to use to configure the environment.
  97722. * @returns a Promise that will resolve when the configuration is done.
  97723. */
  97724. AbstractViewer.prototype._initEnvironment = function (model) {
  97725. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  97726. return Promise.resolve(this.scene);
  97727. };
  97728. /**
  97729. * Alters render settings to reduce features based on hardware feature limitations
  97730. * @param enableHDR Allows the viewer to run in HDR mode.
  97731. */
  97732. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  97733. if (enableHDR === void 0) { enableHDR = true; }
  97734. //flip rendering settings switches based on hardware support
  97735. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  97736. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  97737. //shadows are disabled if there's not enough varyings for a single shadow
  97738. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  97739. this._maxShadows = 0;
  97740. }
  97741. else {
  97742. this._maxShadows = 3;
  97743. }
  97744. //can we render to any >= 16-bit targets (required for HDR)
  97745. var caps = this.engine.getCaps();
  97746. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  97747. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  97748. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  97749. if (linearHalfFloatTargets) {
  97750. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  97751. this._shadowGeneratorBias = 0.002;
  97752. }
  97753. else if (linearFloatTargets) {
  97754. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  97755. this._shadowGeneratorBias = 0.001;
  97756. }
  97757. else {
  97758. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  97759. this._shadowGeneratorBias = 0.001;
  97760. }
  97761. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  97762. };
  97763. /**
  97764. * Injects all the spectre shader in the babylon shader store
  97765. */
  97766. AbstractViewer.prototype._injectCustomShaders = function () {
  97767. var customShaders = this._configuration.customShaders;
  97768. // Inject all the spectre shader in the babylon shader store.
  97769. if (!customShaders) {
  97770. return;
  97771. }
  97772. if (customShaders.shaders) {
  97773. Object.keys(customShaders.shaders).forEach(function (key) {
  97774. // typescript considers a callback "unsafe", so... '!'
  97775. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  97776. });
  97777. }
  97778. if (customShaders.includes) {
  97779. Object.keys(customShaders.includes).forEach(function (key) {
  97780. // typescript considers a callback "unsafe", so... '!'
  97781. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  97782. });
  97783. }
  97784. };
  97785. /**
  97786. * This will extend an object with configuration values.
  97787. * What it practically does it take the keys from the configuration and set them on the object.
  97788. * I the configuration is a tree, it will traverse into the tree.
  97789. * @param object the object to extend
  97790. * @param config the configuration object that will extend the object
  97791. */
  97792. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  97793. var _this = this;
  97794. if (!config)
  97795. return;
  97796. Object.keys(config).forEach(function (key) {
  97797. if (key in object && typeof object[key] !== 'function') {
  97798. // if (typeof object[key] === 'function') return;
  97799. // if it is an object, iterate internally until reaching basic types
  97800. if (typeof object[key] === 'object') {
  97801. _this._extendClassWithConfig(object[key], config[key]);
  97802. }
  97803. else {
  97804. if (config[key] !== undefined) {
  97805. object[key] = config[key];
  97806. }
  97807. }
  97808. }
  97809. });
  97810. };
  97811. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  97812. var behavior;
  97813. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  97814. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  97815. // constructing behavior
  97816. switch (type) {
  97817. case 0 /* AUTOROTATION */:
  97818. this.camera.useAutoRotationBehavior = true;
  97819. behavior = this.camera.autoRotationBehavior;
  97820. break;
  97821. case 1 /* BOUNCING */:
  97822. this.camera.useBouncingBehavior = true;
  97823. behavior = this.camera.bouncingBehavior;
  97824. break;
  97825. case 2 /* FRAMING */:
  97826. this.camera.useFramingBehavior = true;
  97827. behavior = this.camera.framingBehavior;
  97828. break;
  97829. default:
  97830. behavior = null;
  97831. break;
  97832. }
  97833. if (behavior) {
  97834. if (typeof behaviorConfig === "object") {
  97835. this._extendClassWithConfig(behavior, behaviorConfig);
  97836. }
  97837. }
  97838. // post attach configuration. Some functionalities require the attached camera.
  97839. switch (type) {
  97840. case 0 /* AUTOROTATION */:
  97841. break;
  97842. case 1 /* BOUNCING */:
  97843. break;
  97844. case 2 /* FRAMING */:
  97845. if (config.zoomOnBoundingInfo) {
  97846. //payload is an array of meshes
  97847. var meshes = payload;
  97848. var bounding = meshes[0].getHierarchyBoundingVectors();
  97849. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  97850. }
  97851. break;
  97852. }
  97853. };
  97854. return AbstractViewer;
  97855. }());
  97856. exports.AbstractViewer = AbstractViewer;
  97857. /***/ }),
  97858. /* 7 */
  97859. /***/ (function(module, exports) {
  97860. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  97861. /***/ }),
  97862. /* 8 */
  97863. /***/ (function(module, exports) {
  97864. 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}}>";
  97865. /***/ }),
  97866. /* 9 */
  97867. /***/ (function(module, exports) {
  97868. 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=="
  97869. /***/ }),
  97870. /* 10 */
  97871. /***/ (function(module, exports) {
  97872. 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>";
  97873. /***/ }),
  97874. /* 11 */
  97875. /***/ (function(module, exports) {
  97876. 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>";
  97877. /***/ }),
  97878. /* 12 */
  97879. /***/ (function(module, exports) {
  97880. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  97881. /***/ }),
  97882. /* 13 */
  97883. /***/ (function(module, exports) {
  97884. module.exports = "Error loading the model";
  97885. /***/ }),
  97886. /* 14 */
  97887. /***/ (function(module, exports, __webpack_require__) {
  97888. "use strict";
  97889. Object.defineProperty(exports, "__esModule", { value: true });
  97890. var babylonjs_1 = __webpack_require__(0);
  97891. var viewerModel_1 = __webpack_require__(15);
  97892. /**
  97893. * An instance of the class is in charge of loading the model correctly.
  97894. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  97895. *
  97896. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  97897. */
  97898. var ModelLoader = /** @class */ (function () {
  97899. /**
  97900. * Create a new Model loader
  97901. * @param _viewer the viewer using this model loader
  97902. */
  97903. function ModelLoader(_viewer) {
  97904. this._viewer = _viewer;
  97905. this._disposed = false;
  97906. this._loaders = [];
  97907. this._loadId = 0;
  97908. }
  97909. /**
  97910. * Load a model using predefined configuration
  97911. * @param modelConfiguration the modelConfiguration to use to load the model
  97912. */
  97913. ModelLoader.prototype.load = function (modelConfiguration) {
  97914. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  97915. if (!modelConfiguration.url) {
  97916. model.state = viewerModel_1.ModelState.ERROR;
  97917. babylonjs_1.Tools.Error("No URL provided");
  97918. return model;
  97919. }
  97920. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  97921. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  97922. var plugin = modelConfiguration.loader;
  97923. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  97924. meshes.forEach(function (mesh) {
  97925. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  97926. });
  97927. model.meshes = meshes;
  97928. model.particleSystems = particleSystems;
  97929. model.skeletons = skeletons;
  97930. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  97931. var animationGroup = animationGroups_1[_i];
  97932. model.addAnimationGroup(animationGroup);
  97933. }
  97934. model.initAnimations();
  97935. model.onLoadedObservable.notifyObserversWithPromise(model);
  97936. }, function (progressEvent) {
  97937. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  97938. }, function (e, m, exception) {
  97939. model.state = viewerModel_1.ModelState.ERROR;
  97940. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  97941. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  97942. }, plugin);
  97943. if (model.loader.name === "gltf") {
  97944. var gltfLoader = model.loader;
  97945. gltfLoader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  97946. }
  97947. model.loadId = this._loadId++;
  97948. this._loaders.push(model.loader);
  97949. return model;
  97950. };
  97951. ModelLoader.prototype.cancelLoad = function (model) {
  97952. var loader = model.loader || this._loaders[model.loadId];
  97953. // ATM only available in the GLTF Loader
  97954. if (loader && loader.name === "gltf") {
  97955. var gltfLoader = loader;
  97956. gltfLoader.dispose();
  97957. model.state = viewerModel_1.ModelState.CANCELED;
  97958. }
  97959. else {
  97960. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  97961. }
  97962. };
  97963. /**
  97964. * dispose the model loader.
  97965. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  97966. */
  97967. ModelLoader.prototype.dispose = function () {
  97968. this._loaders.forEach(function (loader) {
  97969. if (loader.name === "gltf") {
  97970. loader.dispose();
  97971. }
  97972. });
  97973. this._loaders.length = 0;
  97974. this._disposed = true;
  97975. };
  97976. return ModelLoader;
  97977. }());
  97978. exports.ModelLoader = ModelLoader;
  97979. /***/ }),
  97980. /* 15 */
  97981. /***/ (function(module, exports, __webpack_require__) {
  97982. "use strict";
  97983. Object.defineProperty(exports, "__esModule", { value: true });
  97984. var babylonjs_1 = __webpack_require__(0);
  97985. var modelAnimation_1 = __webpack_require__(16);
  97986. var deepmerge = __webpack_require__(2);
  97987. var ModelState;
  97988. (function (ModelState) {
  97989. ModelState[ModelState["INIT"] = 0] = "INIT";
  97990. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  97991. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  97992. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  97993. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  97994. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  97995. /**
  97996. * The viewer model is a container for all assets representing a sngle loaded model.
  97997. */
  97998. var ViewerModel = /** @class */ (function () {
  97999. function ViewerModel(_viewer, modelConfiguration) {
  98000. this._viewer = _viewer;
  98001. /**
  98002. * the list of meshes that are a part of this model
  98003. */
  98004. this.meshes = [];
  98005. /**
  98006. * ParticleSystems connected to this model
  98007. */
  98008. this.particleSystems = [];
  98009. /**
  98010. * Skeletons defined in this model
  98011. */
  98012. this.skeletons = [];
  98013. this.onLoadedObservable = new babylonjs_1.Observable();
  98014. this.onLoadErrorObservable = new babylonjs_1.Observable();
  98015. this.onLoadProgressObservable = new babylonjs_1.Observable();
  98016. this.onAfterConfigure = new babylonjs_1.Observable();
  98017. this.state = ModelState.INIT;
  98018. this._animations = [];
  98019. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  98020. this._modelConfiguration = deepmerge({}, modelConfiguration);
  98021. this._viewer.models.push(this);
  98022. }
  98023. Object.defineProperty(ViewerModel.prototype, "configuration", {
  98024. /**
  98025. * Get the model's configuration
  98026. */
  98027. get: function () {
  98028. return this._modelConfiguration;
  98029. },
  98030. /**
  98031. * (Re-)set the model's entire configuration
  98032. * @param newConfiguration the new configuration to replace the new one
  98033. */
  98034. set: function (newConfiguration) {
  98035. this._modelConfiguration = newConfiguration;
  98036. this._configureModel();
  98037. },
  98038. enumerable: true,
  98039. configurable: true
  98040. });
  98041. /**
  98042. * Update the current configuration with new values.
  98043. * Configuration will not be overwritten, but merged with the new configuration.
  98044. * Priority is to the new configuration
  98045. * @param newConfiguration the configuration to be merged into the current configuration;
  98046. */
  98047. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  98048. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  98049. this._configureModel();
  98050. };
  98051. ViewerModel.prototype.initAnimations = function () {
  98052. var _this = this;
  98053. this._animations.forEach(function (a) {
  98054. a.dispose();
  98055. });
  98056. this._animations.length = 0;
  98057. // check if this is not a gltf loader and init the animations
  98058. if (this.loader.name !== 'gltf') {
  98059. this.skeletons.forEach(function (skeleton, idx) {
  98060. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  98061. skeleton.getAnimatables().forEach(function (a) {
  98062. if (a.animations[0]) {
  98063. ag.addTargetedAnimation(a.animations[0], a);
  98064. }
  98065. });
  98066. _this.addAnimationGroup(ag);
  98067. });
  98068. }
  98069. if (!this._modelConfiguration)
  98070. return;
  98071. if (this._modelConfiguration.animation) {
  98072. if (this._modelConfiguration.animation.playOnce) {
  98073. this._animations.forEach(function (a) {
  98074. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  98075. });
  98076. }
  98077. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  98078. var animationName = this._modelConfiguration.animation.autoStart === true ?
  98079. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  98080. this.playAnimation(animationName);
  98081. }
  98082. }
  98083. };
  98084. /**
  98085. * Add a new animation group to this model.
  98086. * @param animationGroup the new animation group to be added
  98087. */
  98088. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  98089. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  98090. };
  98091. /**
  98092. * Get the ModelAnimation array
  98093. */
  98094. ViewerModel.prototype.getAnimations = function () {
  98095. return this._animations;
  98096. };
  98097. /**
  98098. * Get the animations' names. Using the names you can play a specific animation.
  98099. */
  98100. ViewerModel.prototype.getAnimationNames = function () {
  98101. return this._animations.map(function (a) { return a.name; });
  98102. };
  98103. /**
  98104. * Get an animation by the provided name. Used mainly when playing n animation.
  98105. * @param name the name of the animation to find
  98106. */
  98107. ViewerModel.prototype._getAnimationByName = function (name) {
  98108. // can't use .find, noe available on IE
  98109. var filtered = this._animations.filter(function (a) { return a.name === name; });
  98110. // what the next line means - if two animations have the same name, they will not be returned!
  98111. if (filtered.length === 1) {
  98112. return filtered[0];
  98113. }
  98114. else {
  98115. return null;
  98116. }
  98117. };
  98118. /**
  98119. * Choose an initialized animation using its name and start playing it
  98120. * @param name the name of the animation to play
  98121. * @returns The model aniamtion to be played.
  98122. */
  98123. ViewerModel.prototype.playAnimation = function (name) {
  98124. var animation = this._getAnimationByName(name);
  98125. if (animation) {
  98126. if (this.currentAnimation) {
  98127. this.currentAnimation.stop();
  98128. }
  98129. this.currentAnimation = animation;
  98130. animation.start();
  98131. return animation;
  98132. }
  98133. else {
  98134. throw new Error("animation not found - " + name);
  98135. }
  98136. };
  98137. ViewerModel.prototype._configureModel = function () {
  98138. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  98139. var updateMeshesWithNoParent = function (variable, value, param) {
  98140. meshesWithNoParent.forEach(function (mesh) {
  98141. if (param) {
  98142. mesh[variable][param] = value;
  98143. }
  98144. else {
  98145. mesh[variable] = value;
  98146. }
  98147. });
  98148. };
  98149. var updateXYZ = function (variable, configValues) {
  98150. if (configValues.x !== undefined) {
  98151. updateMeshesWithNoParent(variable, configValues.x, 'x');
  98152. }
  98153. if (configValues.y !== undefined) {
  98154. updateMeshesWithNoParent(variable, configValues.y, 'y');
  98155. }
  98156. if (configValues.z !== undefined) {
  98157. updateMeshesWithNoParent(variable, configValues.z, 'z');
  98158. }
  98159. if (configValues.w !== undefined) {
  98160. updateMeshesWithNoParent(variable, configValues.w, 'w');
  98161. }
  98162. };
  98163. // position?
  98164. if (this._modelConfiguration.position) {
  98165. updateXYZ('position', this._modelConfiguration.position);
  98166. }
  98167. if (this._modelConfiguration.rotation) {
  98168. //quaternion?
  98169. if (this._modelConfiguration.rotation.w) {
  98170. meshesWithNoParent.forEach(function (mesh) {
  98171. if (!mesh.rotationQuaternion) {
  98172. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  98173. }
  98174. });
  98175. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  98176. }
  98177. else {
  98178. updateXYZ('rotation', this._modelConfiguration.rotation);
  98179. }
  98180. }
  98181. if (this._modelConfiguration.scaling) {
  98182. updateXYZ('scaling', this._modelConfiguration.scaling);
  98183. }
  98184. if (this._modelConfiguration.castShadow) {
  98185. this.meshes.forEach(function (mesh) {
  98186. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  98187. });
  98188. }
  98189. if (this._modelConfiguration.normalize) {
  98190. var center = false;
  98191. var unitSize = false;
  98192. var parentIndex = void 0;
  98193. if (this._modelConfiguration.normalize === true) {
  98194. center = true;
  98195. unitSize = true;
  98196. parentIndex = 0;
  98197. }
  98198. else {
  98199. center = !!this._modelConfiguration.normalize.center;
  98200. unitSize = !!this._modelConfiguration.normalize.unitSize;
  98201. parentIndex = this._modelConfiguration.normalize.parentIndex;
  98202. }
  98203. var meshesToNormalize = [];
  98204. if (parentIndex !== undefined) {
  98205. meshesToNormalize.push(this.meshes[parentIndex]);
  98206. }
  98207. else {
  98208. meshesToNormalize = meshesWithNoParent;
  98209. }
  98210. if (unitSize) {
  98211. meshesToNormalize.forEach(function (mesh) {
  98212. mesh.normalizeToUnitCube(true);
  98213. mesh.computeWorldMatrix(true);
  98214. });
  98215. }
  98216. if (center) {
  98217. meshesToNormalize.forEach(function (mesh) {
  98218. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  98219. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  98220. var halfSizeVec = sizeVec.scale(0.5);
  98221. var center = boundingInfo.min.add(halfSizeVec);
  98222. mesh.position = center.scale(-1);
  98223. // Set on ground.
  98224. mesh.position.y += halfSizeVec.y;
  98225. // Recompute Info.
  98226. mesh.computeWorldMatrix(true);
  98227. });
  98228. }
  98229. }
  98230. this.onAfterConfigure.notifyObservers(this);
  98231. };
  98232. /**
  98233. * Dispose this model, including all of its associated assets.
  98234. */
  98235. ViewerModel.prototype.dispose = function () {
  98236. this.onAfterConfigure.clear();
  98237. this.onLoadedObservable.clear();
  98238. this.onLoadErrorObservable.clear();
  98239. this.onLoadProgressObservable.clear();
  98240. if (this.loader && this.loader.name === "gltf") {
  98241. this.loader.dispose();
  98242. }
  98243. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  98244. this.particleSystems.length = 0;
  98245. this.skeletons.forEach(function (s) { return s.dispose(); });
  98246. this.skeletons.length = 0;
  98247. this._animations.forEach(function (ag) { return ag.dispose(); });
  98248. this._animations.length = 0;
  98249. this.meshes.forEach(function (m) { return m.dispose(); });
  98250. this.meshes.length = 0;
  98251. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  98252. };
  98253. return ViewerModel;
  98254. }());
  98255. exports.ViewerModel = ViewerModel;
  98256. /***/ }),
  98257. /* 16 */
  98258. /***/ (function(module, exports, __webpack_require__) {
  98259. "use strict";
  98260. Object.defineProperty(exports, "__esModule", { value: true });
  98261. /**
  98262. * Animation play mode enum - is the animation looping or playing once
  98263. */
  98264. var AnimationPlayMode;
  98265. (function (AnimationPlayMode) {
  98266. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  98267. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  98268. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  98269. /**
  98270. * An enum representing the current state of an animation object
  98271. */
  98272. var AnimationState;
  98273. (function (AnimationState) {
  98274. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  98275. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  98276. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  98277. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  98278. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  98279. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  98280. /**
  98281. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  98282. * native GroupAnimation class.
  98283. */
  98284. var GroupModelAnimation = /** @class */ (function () {
  98285. /**
  98286. * Create a new GroupModelAnimation object using an AnimationGroup object
  98287. * @param _animationGroup The aniamtion group to base the class on
  98288. */
  98289. function GroupModelAnimation(_animationGroup) {
  98290. var _this = this;
  98291. this._animationGroup = _animationGroup;
  98292. this._state = AnimationState.INIT;
  98293. this._playMode = AnimationPlayMode.LOOP;
  98294. this._animationGroup.onAnimationEndObservable.add(function () {
  98295. _this.stop();
  98296. _this._state = AnimationState.ENDED;
  98297. });
  98298. }
  98299. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  98300. /**
  98301. * Get the animation's name
  98302. */
  98303. get: function () {
  98304. return this._animationGroup.name;
  98305. },
  98306. enumerable: true,
  98307. configurable: true
  98308. });
  98309. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  98310. /**
  98311. * Get the current animation's state
  98312. */
  98313. get: function () {
  98314. return this._state;
  98315. },
  98316. enumerable: true,
  98317. configurable: true
  98318. });
  98319. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  98320. /**
  98321. * Gets the speed ratio to use for all animations
  98322. */
  98323. get: function () {
  98324. return this._animationGroup.speedRatio;
  98325. },
  98326. /**
  98327. * Sets the speed ratio to use for all animations
  98328. */
  98329. set: function (value) {
  98330. this._animationGroup.speedRatio = value;
  98331. },
  98332. enumerable: true,
  98333. configurable: true
  98334. });
  98335. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  98336. /**
  98337. * Get the max numbers of frame available in the animation group
  98338. *
  98339. * In correlation to an arry, this would be ".length"
  98340. */
  98341. get: function () {
  98342. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  98343. var keys = ta.animation.getKeys();
  98344. return keys[keys.length - 1].frame;
  98345. });
  98346. return Math.max.apply(null, animationFrames);
  98347. },
  98348. enumerable: true,
  98349. configurable: true
  98350. });
  98351. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  98352. /**
  98353. * Get the current frame playing right now.
  98354. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  98355. *
  98356. * In correlation to an array, this would be the current index
  98357. */
  98358. get: function () {
  98359. // get the first currentFrame found
  98360. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  98361. var animatable = this._animationGroup.animatables[i];
  98362. var animations = animatable.getAnimations();
  98363. if (!animations || !animations.length) {
  98364. continue;
  98365. }
  98366. for (var idx = 0; idx < animations.length; ++idx) {
  98367. if (animations[idx].currentFrame) {
  98368. return animations[idx].currentFrame;
  98369. }
  98370. }
  98371. }
  98372. return 0;
  98373. },
  98374. enumerable: true,
  98375. configurable: true
  98376. });
  98377. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  98378. /**
  98379. * Get the FPS value of this animation
  98380. */
  98381. get: function () {
  98382. // get the first currentFrame found
  98383. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  98384. var animatable = this._animationGroup.animatables[i];
  98385. var animations = animatable.getAnimations();
  98386. if (!animations || !animations.length) {
  98387. continue;
  98388. }
  98389. for (var idx = 0; idx < animations.length; ++idx) {
  98390. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  98391. return animations[idx].animation.framePerSecond;
  98392. }
  98393. }
  98394. }
  98395. return 0;
  98396. },
  98397. enumerable: true,
  98398. configurable: true
  98399. });
  98400. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  98401. /**
  98402. * What is the animation'S play mode (looping or played once)
  98403. */
  98404. get: function () {
  98405. return this._playMode;
  98406. },
  98407. /**
  98408. * Set the play mode.
  98409. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  98410. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  98411. */
  98412. set: function (value) {
  98413. if (value === this._playMode) {
  98414. return;
  98415. }
  98416. this._playMode = value;
  98417. if (this.state === AnimationState.PLAYING) {
  98418. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  98419. }
  98420. else {
  98421. this._animationGroup.reset();
  98422. this._state = AnimationState.INIT;
  98423. }
  98424. },
  98425. enumerable: true,
  98426. configurable: true
  98427. });
  98428. /**
  98429. * Reset the animation group
  98430. */
  98431. GroupModelAnimation.prototype.reset = function () {
  98432. this._animationGroup.reset();
  98433. };
  98434. /**
  98435. * Restart the animation group
  98436. */
  98437. GroupModelAnimation.prototype.restart = function () {
  98438. this._animationGroup.restart();
  98439. };
  98440. /**
  98441. *
  98442. * @param frameNumber Go to a specific frame in the animation
  98443. */
  98444. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  98445. // this._animationGroup.goToFrame(frameNumber);
  98446. this._animationGroup['_animatables'].forEach(function (a) {
  98447. a.goToFrame(frameNumber);
  98448. });
  98449. };
  98450. /**
  98451. * Start playing the animation.
  98452. */
  98453. GroupModelAnimation.prototype.start = function () {
  98454. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  98455. if (this._animationGroup.isStarted) {
  98456. this._state = AnimationState.PLAYING;
  98457. }
  98458. };
  98459. /**
  98460. * Pause the animation
  98461. */
  98462. GroupModelAnimation.prototype.pause = function () {
  98463. this._animationGroup.pause();
  98464. this._state = AnimationState.PAUSED;
  98465. };
  98466. /**
  98467. * Stop the animation.
  98468. * This will fail silently if the animation group is already stopped.
  98469. */
  98470. GroupModelAnimation.prototype.stop = function () {
  98471. this._animationGroup.stop();
  98472. if (!this._animationGroup.isStarted) {
  98473. this._state = AnimationState.STOPPED;
  98474. }
  98475. };
  98476. /**
  98477. * Dispose this animation object.
  98478. */
  98479. GroupModelAnimation.prototype.dispose = function () {
  98480. this._animationGroup.dispose();
  98481. };
  98482. return GroupModelAnimation;
  98483. }());
  98484. exports.GroupModelAnimation = GroupModelAnimation;
  98485. /***/ }),
  98486. /* 17 */
  98487. /***/ (function(module, exports, __webpack_require__) {
  98488. module.exports = __webpack_require__(18);
  98489. /***/ }),
  98490. /* 18 */
  98491. /***/ (function(module, exports, __webpack_require__) {
  98492. "use strict";
  98493. Object.defineProperty(exports, "__esModule", { value: true });
  98494. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  98495. var mappers_1 = __webpack_require__(1);
  98496. exports.mapperManager = mappers_1.mapperManager;
  98497. var viewerManager_1 = __webpack_require__(4);
  98498. exports.viewerManager = viewerManager_1.viewerManager;
  98499. var defaultViewer_1 = __webpack_require__(5);
  98500. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  98501. var viewer_1 = __webpack_require__(6);
  98502. exports.AbstractViewer = viewer_1.AbstractViewer;
  98503. var modelLoader_1 = __webpack_require__(14);
  98504. exports.ModelLoader = modelLoader_1.ModelLoader;
  98505. var viewerModel_1 = __webpack_require__(15);
  98506. exports.ViewerModel = viewerModel_1.ViewerModel;
  98507. exports.ModelState = viewerModel_1.ModelState;
  98508. var modelAnimation_1 = __webpack_require__(16);
  98509. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  98510. exports.AnimationState = modelAnimation_1.AnimationState;
  98511. /**
  98512. * BabylonJS Viewer
  98513. *
  98514. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  98515. */
  98516. var babylonjs_1 = __webpack_require__(0);
  98517. // load needed modules.
  98518. __webpack_require__(34);
  98519. __webpack_require__(35);
  98520. var initializer_1 = __webpack_require__(36);
  98521. exports.InitTags = initializer_1.InitTags;
  98522. // promise polyfill, if needed!
  98523. babylonjs_1.PromisePolyfill.Apply();
  98524. exports.disableInit = false;
  98525. document.addEventListener("DOMContentLoaded", init);
  98526. function init(event) {
  98527. document.removeEventListener("DOMContentLoaded", init);
  98528. if (exports.disableInit)
  98529. return;
  98530. initializer_1.InitTags();
  98531. }
  98532. /**
  98533. * Dispose all viewers currently registered
  98534. */
  98535. function disposeAll() {
  98536. viewerManager_1.viewerManager.dispose();
  98537. mappers_1.mapperManager.dispose();
  98538. }
  98539. exports.disposeAll = disposeAll;
  98540. /***/ }),
  98541. /* 19 */
  98542. /***/ (function(module, exports) {
  98543. var g;
  98544. // This works in non-strict mode
  98545. g = (function() {
  98546. return this;
  98547. })();
  98548. try {
  98549. // This works if eval is allowed (see CSP)
  98550. g = g || Function("return this")() || (1,eval)("this");
  98551. } catch(e) {
  98552. // This works if the window reference is available
  98553. if(typeof window === "object")
  98554. g = window;
  98555. }
  98556. // g can still be undefined, but nothing to do about it...
  98557. // We return undefined, instead of nothing here, so it's
  98558. // easier to handle this case. if(!global) { ...}
  98559. module.exports = g;
  98560. /***/ }),
  98561. /* 20 */
  98562. /***/ (function(module, exports) {
  98563. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  98564. module.exports = CANNON;
  98565. /***/ }),
  98566. /* 21 */
  98567. /***/ (function(module, exports) {
  98568. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  98569. module.exports = OIMO;
  98570. /***/ }),
  98571. /* 22 */
  98572. /***/ (function(module, exports) {
  98573. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  98574. module.exports = earcut;
  98575. /***/ }),
  98576. /* 23 */
  98577. /***/ (function(module, exports, __webpack_require__) {
  98578. "use strict";
  98579. Object.defineProperty(exports, "__esModule", { value: true });
  98580. var babylonjs_1 = __webpack_require__(0);
  98581. var helper_1 = __webpack_require__(3);
  98582. /**
  98583. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  98584. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  98585. */
  98586. var TemplateManager = /** @class */ (function () {
  98587. function TemplateManager(containerElement) {
  98588. this.containerElement = containerElement;
  98589. this.templates = {};
  98590. this.onTemplateInit = new babylonjs_1.Observable();
  98591. this.onTemplateLoaded = new babylonjs_1.Observable();
  98592. this.onTemplateStateChange = new babylonjs_1.Observable();
  98593. this.onAllLoaded = new babylonjs_1.Observable();
  98594. this.onEventTriggered = new babylonjs_1.Observable();
  98595. this.eventManager = new eventManager_1.EventManager(this);
  98596. }
  98597. /**
  98598. * Initialize the template(s) for the viewer. Called bay the Viewer class
  98599. * @param templates the templates to be used to initialize the main template
  98600. */
  98601. TemplateManager.prototype.initTemplate = function (templates) {
  98602. var _this = this;
  98603. var internalInit = function (dependencyMap, name, parentTemplate) {
  98604. //init template
  98605. var template = _this.templates[name];
  98606. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  98607. return internalInit(dependencyMap[childName], childName, template);
  98608. });
  98609. // register the observers
  98610. //template.onLoaded.add(() => {
  98611. var addToParent = function () {
  98612. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  98613. template.appendTo(containingElement);
  98614. _this._checkLoadedState();
  98615. };
  98616. if (parentTemplate && !parentTemplate.parent) {
  98617. parentTemplate.onAppended.add(function () {
  98618. addToParent();
  98619. });
  98620. }
  98621. else {
  98622. addToParent();
  98623. }
  98624. //});
  98625. return template;
  98626. };
  98627. //build the html tree
  98628. return this._buildHTMLTree(templates).then(function (htmlTree) {
  98629. if (_this.templates['main']) {
  98630. internalInit(htmlTree, 'main');
  98631. }
  98632. else {
  98633. _this._checkLoadedState();
  98634. }
  98635. return;
  98636. });
  98637. };
  98638. /**
  98639. *
  98640. * This function will create a simple map with child-dependencies of the template html tree.
  98641. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  98642. * It is expected that the main template will be called main!
  98643. *
  98644. * @param templates
  98645. */
  98646. TemplateManager.prototype._buildHTMLTree = function (templates) {
  98647. var _this = this;
  98648. var promises = Object.keys(templates).map(function (name) {
  98649. // if the template was overridden
  98650. if (!templates[name])
  98651. return Promise.resolve(false);
  98652. // else - we have a template, let's do our job!
  98653. var template = new Template(name, templates[name]);
  98654. template.onLoaded.add(function () {
  98655. _this.onTemplateLoaded.notifyObservers(template);
  98656. });
  98657. template.onStateChange.add(function () {
  98658. _this.onTemplateStateChange.notifyObservers(template);
  98659. });
  98660. _this.onTemplateInit.notifyObservers(template);
  98661. // make sure the global onEventTriggered is called as well
  98662. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  98663. _this.templates[name] = template;
  98664. return template.initPromise;
  98665. });
  98666. return Promise.all(promises).then(function () {
  98667. var templateStructure = {};
  98668. // now iterate through all templates and check for children:
  98669. var buildTree = function (parentObject, name) {
  98670. _this.templates[name].isInHtmlTree = true;
  98671. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  98672. childNodes.forEach(function (element) {
  98673. parentObject[element] = {};
  98674. buildTree(parentObject[element], element);
  98675. });
  98676. };
  98677. if (_this.templates['main']) {
  98678. buildTree(templateStructure, "main");
  98679. }
  98680. return templateStructure;
  98681. });
  98682. };
  98683. /**
  98684. * Get the canvas in the template tree.
  98685. * There must be one and only one canvas inthe template.
  98686. */
  98687. TemplateManager.prototype.getCanvas = function () {
  98688. return this.containerElement.querySelector('canvas');
  98689. };
  98690. /**
  98691. * Get a specific template from the template tree
  98692. * @param name the name of the template to load
  98693. */
  98694. TemplateManager.prototype.getTemplate = function (name) {
  98695. return this.templates[name];
  98696. };
  98697. TemplateManager.prototype._checkLoadedState = function () {
  98698. var _this = this;
  98699. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  98700. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  98701. });
  98702. if (done) {
  98703. this.onAllLoaded.notifyObservers(this);
  98704. }
  98705. };
  98706. /**
  98707. * Dispose the template manager
  98708. */
  98709. TemplateManager.prototype.dispose = function () {
  98710. var _this = this;
  98711. // dispose all templates
  98712. Object.keys(this.templates).forEach(function (template) {
  98713. _this.templates[template].dispose();
  98714. });
  98715. this.templates = {};
  98716. this.eventManager.dispose();
  98717. this.onTemplateInit.clear();
  98718. this.onAllLoaded.clear();
  98719. this.onEventTriggered.clear();
  98720. this.onTemplateLoaded.clear();
  98721. this.onTemplateStateChange.clear();
  98722. };
  98723. return TemplateManager;
  98724. }());
  98725. exports.TemplateManager = TemplateManager;
  98726. var Handlebars = __webpack_require__(24);
  98727. var eventManager_1 = __webpack_require__(25);
  98728. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  98729. Handlebars.registerHelper('eachInMap', function (map, block) {
  98730. var out = '';
  98731. Object.keys(map).map(function (prop) {
  98732. var data = map[prop];
  98733. if (typeof data === 'object') {
  98734. data.id = data.id || prop;
  98735. out += block.fn(data);
  98736. }
  98737. else {
  98738. out += block.fn({ id: prop, value: data });
  98739. }
  98740. });
  98741. return out;
  98742. });
  98743. /**
  98744. * This class represents a single template in the viewer's template tree.
  98745. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  98746. * A template is injected using the template manager in the correct position.
  98747. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  98748. *
  98749. * For further information please refer to the documentation page, https://doc.babylonjs.com
  98750. */
  98751. var Template = /** @class */ (function () {
  98752. function Template(name, _configuration) {
  98753. var _this = this;
  98754. this.name = name;
  98755. this._configuration = _configuration;
  98756. this.onLoaded = new babylonjs_1.Observable();
  98757. this.onAppended = new babylonjs_1.Observable();
  98758. this.onStateChange = new babylonjs_1.Observable();
  98759. this.onEventTriggered = new babylonjs_1.Observable();
  98760. this.loadRequests = [];
  98761. this.isLoaded = false;
  98762. this.isShown = false;
  98763. this.isInHtmlTree = false;
  98764. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  98765. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  98766. if (htmlTemplate) {
  98767. _this._htmlTemplate = htmlTemplate;
  98768. var compiledTemplate = Handlebars.compile(htmlTemplate);
  98769. var config = _this._configuration.params || {};
  98770. var rawHtml = compiledTemplate(config);
  98771. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  98772. _this.isLoaded = true;
  98773. _this.isShown = true;
  98774. _this.onLoaded.notifyObservers(_this);
  98775. }
  98776. return _this;
  98777. });
  98778. }
  98779. /**
  98780. * Some templates have parameters (like background color for example).
  98781. * The parameters are provided to Handlebars which in turn generates the template.
  98782. * This function will update the template with the new parameters
  98783. *
  98784. * @param params the new template parameters
  98785. */
  98786. Template.prototype.updateParams = function (params) {
  98787. this._configuration.params = params;
  98788. // update the template
  98789. if (this.isLoaded) {
  98790. this.dispose();
  98791. }
  98792. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  98793. var config = this._configuration.params || {};
  98794. var rawHtml = compiledTemplate(config);
  98795. this._fragment = document.createRange().createContextualFragment(rawHtml);
  98796. if (this.parent) {
  98797. this.appendTo(this.parent, true);
  98798. }
  98799. };
  98800. Object.defineProperty(Template.prototype, "configuration", {
  98801. /**
  98802. * Get the template'S configuration
  98803. */
  98804. get: function () {
  98805. return this._configuration;
  98806. },
  98807. enumerable: true,
  98808. configurable: true
  98809. });
  98810. /**
  98811. * A template can be a parent element for other templates or HTML elements.
  98812. * This function will deliver all child HTML elements of this template.
  98813. */
  98814. Template.prototype.getChildElements = function () {
  98815. var childrenArray = [];
  98816. //Edge and IE don't support frage,ent.children
  98817. var children = this._fragment.children;
  98818. if (!children) {
  98819. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  98820. children = this._fragment.querySelectorAll('*');
  98821. }
  98822. for (var i = 0; i < children.length; ++i) {
  98823. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  98824. }
  98825. return childrenArray;
  98826. };
  98827. /**
  98828. * Appending the template to a parent HTML element.
  98829. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  98830. * @param parent the parent to which the template is added
  98831. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  98832. */
  98833. Template.prototype.appendTo = function (parent, forceRemove) {
  98834. var _this = this;
  98835. if (this.parent) {
  98836. if (forceRemove) {
  98837. this.parent.removeChild(this._fragment);
  98838. }
  98839. else {
  98840. return;
  98841. }
  98842. }
  98843. this.parent = parent;
  98844. if (this._configuration.id) {
  98845. this.parent.id = this._configuration.id;
  98846. }
  98847. this._fragment = this.parent.appendChild(this._fragment);
  98848. // appended only one frame after.
  98849. setTimeout(function () {
  98850. _this._registerEvents();
  98851. _this.onAppended.notifyObservers(_this);
  98852. });
  98853. };
  98854. /**
  98855. * Show the template using the provided visibilityFunction, or natively using display: flex.
  98856. * The provided function returns a promise that should be fullfilled when the element is shown.
  98857. * Since it is a promise async operations are more than possible.
  98858. * See the default viewer for an opacity example.
  98859. * @param visibilityFunction The function to execute to show the template.
  98860. */
  98861. Template.prototype.show = function (visibilityFunction) {
  98862. var _this = this;
  98863. if (this._isHiding)
  98864. return Promise.resolve(this);
  98865. return Promise.resolve().then(function () {
  98866. _this._isShowing = true;
  98867. if (visibilityFunction) {
  98868. return visibilityFunction(_this);
  98869. }
  98870. else {
  98871. // flex? box? should this be configurable easier than the visibilityFunction?
  98872. _this.parent.style.display = 'flex';
  98873. return _this;
  98874. }
  98875. }).then(function () {
  98876. _this.isShown = true;
  98877. _this._isShowing = false;
  98878. _this.onStateChange.notifyObservers(_this);
  98879. return _this;
  98880. });
  98881. };
  98882. /**
  98883. * Hide the template using the provided visibilityFunction, or natively using display: none.
  98884. * The provided function returns a promise that should be fullfilled when the element is hidden.
  98885. * Since it is a promise async operations are more than possible.
  98886. * See the default viewer for an opacity example.
  98887. * @param visibilityFunction The function to execute to show the template.
  98888. */
  98889. Template.prototype.hide = function (visibilityFunction) {
  98890. var _this = this;
  98891. if (this._isShowing)
  98892. return Promise.resolve(this);
  98893. return Promise.resolve().then(function () {
  98894. _this._isHiding = true;
  98895. if (visibilityFunction) {
  98896. return visibilityFunction(_this);
  98897. }
  98898. else {
  98899. // flex? box? should this be configurable easier than the visibilityFunction?
  98900. _this.parent.style.display = 'hide';
  98901. return _this;
  98902. }
  98903. }).then(function () {
  98904. _this.isShown = false;
  98905. _this._isHiding = false;
  98906. _this.onStateChange.notifyObservers(_this);
  98907. return _this;
  98908. });
  98909. };
  98910. /**
  98911. * Dispose this template
  98912. */
  98913. Template.prototype.dispose = function () {
  98914. this.onAppended.clear();
  98915. this.onEventTriggered.clear();
  98916. this.onLoaded.clear();
  98917. this.onStateChange.clear();
  98918. this.isLoaded = false;
  98919. // remove from parent
  98920. try {
  98921. this.parent.removeChild(this._fragment);
  98922. }
  98923. catch (e) {
  98924. //noop
  98925. }
  98926. this.loadRequests.forEach(function (request) {
  98927. request.abort();
  98928. });
  98929. if (this._registeredEvents) {
  98930. this._registeredEvents.forEach(function (evt) {
  98931. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  98932. });
  98933. }
  98934. delete this._fragment;
  98935. };
  98936. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  98937. var _this = this;
  98938. if (!templateConfig) {
  98939. return Promise.reject('No templateConfig provided');
  98940. }
  98941. else if (templateConfig.html !== undefined) {
  98942. return Promise.resolve(templateConfig.html);
  98943. }
  98944. else {
  98945. var location_1 = this._getTemplateLocation(templateConfig);
  98946. if (helper_1.isUrl(location_1)) {
  98947. return new Promise(function (resolve, reject) {
  98948. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  98949. resolve(data);
  98950. }, undefined, undefined, false, function (request, error) {
  98951. reject(error);
  98952. });
  98953. _this.loadRequests.push(fileRequest);
  98954. });
  98955. }
  98956. else {
  98957. location_1 = location_1.replace('#', '');
  98958. var element = document.getElementById(location_1);
  98959. if (element) {
  98960. return Promise.resolve(element.innerHTML);
  98961. }
  98962. else {
  98963. return Promise.reject('Template ID not found');
  98964. }
  98965. }
  98966. }
  98967. };
  98968. Template.prototype._registerEvents = function () {
  98969. var _this = this;
  98970. this._registeredEvents = this._registeredEvents || [];
  98971. if (this._registeredEvents.length) {
  98972. // first remove the registered events
  98973. this._registeredEvents.forEach(function (evt) {
  98974. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  98975. });
  98976. }
  98977. if (this._configuration.events) {
  98978. var _loop_1 = function (eventName) {
  98979. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  98980. var functionToFire_1 = function (selector, event) {
  98981. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  98982. };
  98983. // if boolean, set the parent as the event listener
  98984. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  98985. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  98986. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  98987. this_1._registeredEvents.push({
  98988. htmlElement: this_1.parent,
  98989. eventName: eventName,
  98990. function: binding
  98991. });
  98992. }
  98993. else if (typeof this_1._configuration.events[eventName] === 'object') {
  98994. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  98995. // strict null checl is working incorrectly, must override:
  98996. var event_1 = this_1._configuration.events[eventName] || {};
  98997. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  98998. if (selector && selector.indexOf('#') !== 0) {
  98999. selector = '#' + selector;
  99000. }
  99001. var htmlElement = _this.parent.querySelector(selector);
  99002. if (htmlElement) {
  99003. var binding = functionToFire_1.bind(_this, selector);
  99004. htmlElement.addEventListener(eventName, binding, false);
  99005. _this._registeredEvents.push({
  99006. htmlElement: htmlElement,
  99007. eventName: eventName,
  99008. function: binding
  99009. });
  99010. }
  99011. });
  99012. }
  99013. }
  99014. };
  99015. var this_1 = this;
  99016. for (var eventName in this._configuration.events) {
  99017. _loop_1(eventName);
  99018. }
  99019. }
  99020. };
  99021. Template.prototype._getTemplateLocation = function (templateConfig) {
  99022. if (!templateConfig || typeof templateConfig === 'string') {
  99023. return templateConfig;
  99024. }
  99025. else {
  99026. return templateConfig.location;
  99027. }
  99028. };
  99029. return Template;
  99030. }());
  99031. exports.Template = Template;
  99032. /***/ }),
  99033. /* 24 */
  99034. /***/ (function(module, exports, __webpack_require__) {
  99035. /**!
  99036. @license
  99037. handlebars v4.0.11
  99038. Copyright (C) 2011-2017 by Yehuda Katz
  99039. Permission is hereby granted, free of charge, to any person obtaining a copy
  99040. of this software and associated documentation files (the "Software"), to deal
  99041. in the Software without restriction, including without limitation the rights
  99042. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  99043. copies of the Software, and to permit persons to whom the Software is
  99044. furnished to do so, subject to the following conditions:
  99045. The above copyright notice and this permission notice shall be included in
  99046. all copies or substantial portions of the Software.
  99047. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  99048. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  99049. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  99050. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  99051. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  99052. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  99053. THE SOFTWARE.
  99054. */
  99055. !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],
  99056. 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){
  99057. 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"]}])});
  99058. /***/ }),
  99059. /* 25 */
  99060. /***/ (function(module, exports, __webpack_require__) {
  99061. "use strict";
  99062. Object.defineProperty(exports, "__esModule", { value: true });
  99063. /**
  99064. * The EventManager is in charge of registering user interctions with the viewer.
  99065. * It is used in the TemplateManager
  99066. */
  99067. var EventManager = /** @class */ (function () {
  99068. function EventManager(_templateManager) {
  99069. var _this = this;
  99070. this._templateManager = _templateManager;
  99071. this._callbacksContainer = {};
  99072. this._templateManager.onEventTriggered.add(function (eventData) {
  99073. _this._eventTriggered(eventData);
  99074. });
  99075. }
  99076. /**
  99077. * Register a new callback to a specific template.
  99078. * The best example for the usage can be found in the DefaultViewer
  99079. *
  99080. * @param templateName the templateName to register the event to
  99081. * @param callback The callback to be executed
  99082. * @param eventType the type of event to register
  99083. * @param selector an optional selector. if not defined the parent object in the template will be selected
  99084. */
  99085. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  99086. if (!this._callbacksContainer[templateName]) {
  99087. this._callbacksContainer[templateName] = [];
  99088. }
  99089. this._callbacksContainer[templateName].push({
  99090. eventType: eventType,
  99091. callback: callback
  99092. });
  99093. };
  99094. /**
  99095. * This will remove a registered event from the defined template.
  99096. * Each one of the variables apart from the template name are optional, but one must be provided.
  99097. *
  99098. * @param templateName the templateName
  99099. * @param callback the callback to remove (optional)
  99100. * @param eventType the event type to remove (optional)
  99101. * @param selector the selector from which to remove the event (optional)
  99102. */
  99103. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  99104. var callbackDefs = this._callbacksContainer[templateName] || [];
  99105. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  99106. };
  99107. EventManager.prototype._eventTriggered = function (data) {
  99108. var templateName = data.template.name;
  99109. var eventType = data.event.type;
  99110. var selector = data.selector;
  99111. var callbackDefs = this._callbacksContainer[templateName] || [];
  99112. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  99113. callbackDef.callback(data);
  99114. });
  99115. };
  99116. /**
  99117. * Dispose the event manager
  99118. */
  99119. EventManager.prototype.dispose = function () {
  99120. this._callbacksContainer = {};
  99121. };
  99122. return EventManager;
  99123. }());
  99124. exports.EventManager = EventManager;
  99125. /***/ }),
  99126. /* 26 */
  99127. /***/ (function(module, exports, __webpack_require__) {
  99128. "use strict";
  99129. Object.defineProperty(exports, "__esModule", { value: true });
  99130. var mappers_1 = __webpack_require__(1);
  99131. var types_1 = __webpack_require__(27);
  99132. var deepmerge = __webpack_require__(2);
  99133. var babylonjs_1 = __webpack_require__(0);
  99134. /**
  99135. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  99136. * parse the object and return a conform ViewerConfiguration.
  99137. * It is a private member of the scene.
  99138. */
  99139. var ConfigurationLoader = /** @class */ (function () {
  99140. function ConfigurationLoader(_enableCache) {
  99141. if (_enableCache === void 0) { _enableCache = false; }
  99142. this._enableCache = _enableCache;
  99143. this._configurationCache = {};
  99144. this._loadRequests = [];
  99145. }
  99146. /**
  99147. * load a configuration object that is defined in the initial configuration provided.
  99148. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  99149. *
  99150. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  99151. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  99152. * @returns A promise that delivers the extended viewer configuration, when done.
  99153. */
  99154. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  99155. var _this = this;
  99156. if (initConfig === void 0) { initConfig = {}; }
  99157. var loadedConfig = deepmerge({}, initConfig);
  99158. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  99159. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  99160. if (loadedConfig.configuration) {
  99161. var mapperType_1 = "json";
  99162. return Promise.resolve().then(function () {
  99163. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  99164. // a file to load
  99165. var url = '';
  99166. if (typeof loadedConfig.configuration === "string") {
  99167. url = loadedConfig.configuration;
  99168. }
  99169. // if configuration is an object
  99170. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  99171. url = loadedConfig.configuration.url;
  99172. var type = loadedConfig.configuration.mapper;
  99173. // empty string?
  99174. if (!type) {
  99175. // load mapper type from filename / url
  99176. type = loadedConfig.configuration.url.split('.').pop();
  99177. }
  99178. mapperType_1 = type || mapperType_1;
  99179. }
  99180. return _this._loadFile(url);
  99181. }
  99182. else {
  99183. if (typeof loadedConfig.configuration === "object") {
  99184. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  99185. return loadedConfig.configuration.payload || {};
  99186. }
  99187. return {};
  99188. }
  99189. }).then(function (data) {
  99190. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  99191. var parsed = mapper.map(data);
  99192. var merged = deepmerge(loadedConfig, parsed);
  99193. if (callback)
  99194. callback(merged);
  99195. return merged;
  99196. });
  99197. }
  99198. else {
  99199. if (callback)
  99200. callback(loadedConfig);
  99201. return Promise.resolve(loadedConfig);
  99202. }
  99203. };
  99204. /**
  99205. * Dispose the configuration loader. This will cancel file requests, if active.
  99206. */
  99207. ConfigurationLoader.prototype.dispose = function () {
  99208. this._loadRequests.forEach(function (request) {
  99209. request.abort();
  99210. });
  99211. this._loadRequests.length = 0;
  99212. };
  99213. ConfigurationLoader.prototype._loadFile = function (url) {
  99214. var _this = this;
  99215. var cacheReference = this._configurationCache;
  99216. if (this._enableCache && cacheReference[url]) {
  99217. return Promise.resolve(cacheReference[url]);
  99218. }
  99219. return new Promise(function (resolve, reject) {
  99220. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  99221. var idx = _this._loadRequests.indexOf(fileRequest);
  99222. if (idx !== -1)
  99223. _this._loadRequests.splice(idx, 1);
  99224. if (_this._enableCache)
  99225. cacheReference[url] = result;
  99226. resolve(result);
  99227. }, undefined, undefined, false, function (request, error) {
  99228. var idx = _this._loadRequests.indexOf(fileRequest);
  99229. if (idx !== -1)
  99230. _this._loadRequests.splice(idx, 1);
  99231. reject(error);
  99232. });
  99233. _this._loadRequests.push(fileRequest);
  99234. });
  99235. };
  99236. return ConfigurationLoader;
  99237. }());
  99238. exports.ConfigurationLoader = ConfigurationLoader;
  99239. /***/ }),
  99240. /* 27 */
  99241. /***/ (function(module, exports, __webpack_require__) {
  99242. "use strict";
  99243. Object.defineProperty(exports, "__esModule", { value: true });
  99244. var minimal_1 = __webpack_require__(28);
  99245. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  99246. var default_1 = __webpack_require__(29);
  99247. exports.defaultConfiguration = default_1.defaultConfiguration;
  99248. var getConfigurationType = function (type) {
  99249. switch (type) {
  99250. case 'default':
  99251. return default_1.defaultConfiguration;
  99252. case 'minimal':
  99253. return minimal_1.minimalConfiguration;
  99254. case 'none':
  99255. return {};
  99256. default:
  99257. return default_1.defaultConfiguration;
  99258. }
  99259. };
  99260. exports.getConfigurationType = getConfigurationType;
  99261. /***/ }),
  99262. /* 28 */
  99263. /***/ (function(module, exports, __webpack_require__) {
  99264. "use strict";
  99265. Object.defineProperty(exports, "__esModule", { value: true });
  99266. exports.minimalConfiguration = {
  99267. version: "0.1",
  99268. templates: {
  99269. main: {
  99270. html: __webpack_require__(7)
  99271. },
  99272. loadingScreen: {
  99273. html: __webpack_require__(8),
  99274. params: {
  99275. backgroundColor: "#000000",
  99276. 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"
  99277. }
  99278. },
  99279. viewer: {
  99280. html: __webpack_require__(10),
  99281. },
  99282. overlay: {
  99283. html: __webpack_require__(11),
  99284. params: {
  99285. closeImage: __webpack_require__(12),
  99286. closeText: 'Close'
  99287. }
  99288. },
  99289. error: {
  99290. html: __webpack_require__(13)
  99291. }
  99292. },
  99293. engine: {
  99294. antialiasing: true
  99295. }
  99296. };
  99297. /***/ }),
  99298. /* 29 */
  99299. /***/ (function(module, exports, __webpack_require__) {
  99300. "use strict";
  99301. Object.defineProperty(exports, "__esModule", { value: true });
  99302. exports.defaultConfiguration = {
  99303. version: "3.2.0-alpha4",
  99304. templates: {
  99305. main: {
  99306. html: __webpack_require__(7)
  99307. },
  99308. loadingScreen: {
  99309. html: __webpack_require__(8),
  99310. params: {
  99311. backgroundColor: "#000000",
  99312. loadingImage: __webpack_require__(9)
  99313. }
  99314. },
  99315. viewer: {
  99316. html: __webpack_require__(10),
  99317. events: {
  99318. pointerout: true,
  99319. pointerdown: true,
  99320. pointerup: true
  99321. }
  99322. },
  99323. navBar: {
  99324. html: __webpack_require__(30),
  99325. params: {
  99326. buttons: {
  99327. /*"help-button": {
  99328. altText: "Help",
  99329. image: require('../../../assets/img/help-circle.png')
  99330. },*/
  99331. "fullscreen-button": {
  99332. altText: "Fullscreen",
  99333. image: __webpack_require__(31)
  99334. }
  99335. },
  99336. visibilityTimeout: 2000
  99337. },
  99338. events: {
  99339. pointerdown: { 'fullscreen-button': true /*, '#help-button': true*/ },
  99340. pointerover: true
  99341. }
  99342. },
  99343. overlay: {
  99344. html: __webpack_require__(11),
  99345. params: {
  99346. closeImage: __webpack_require__(12),
  99347. closeText: 'Close'
  99348. }
  99349. },
  99350. help: {
  99351. html: __webpack_require__(32)
  99352. },
  99353. share: {
  99354. html: __webpack_require__(33)
  99355. },
  99356. error: {
  99357. html: __webpack_require__(13)
  99358. }
  99359. },
  99360. camera: {
  99361. behaviors: {
  99362. autoRotate: 0,
  99363. framing: {
  99364. type: 2,
  99365. zoomOnBoundingInfo: true,
  99366. zoomStopsAnimation: false
  99367. }
  99368. }
  99369. },
  99370. /*lights: {
  99371. "default": {
  99372. type: 1,
  99373. shadowEnabled: true,
  99374. direction: { x: -0.2, y: -0.8, z: 0 },
  99375. position: { x: 10, y: 10, z: 0 },
  99376. intensity: 4.5,
  99377. shadowConfig: {
  99378. useBlurExponentialShadowMap: true,
  99379. useKernelBlur: true,
  99380. blurKernel: 64,
  99381. blurScale: 4
  99382. }
  99383. }
  99384. },*/
  99385. skybox: {
  99386. /*cubeTexture: {
  99387. url: 'https://playground.babylonjs.com/textures/environment.dds',
  99388. gammaSpace: false
  99389. },*/
  99390. pbr: true,
  99391. blur: 0.7,
  99392. infiniteDIstance: false,
  99393. },
  99394. ground: true,
  99395. engine: {
  99396. antialiasing: true
  99397. },
  99398. scene: {
  99399. imageProcessingConfiguration: {
  99400. exposure: 1.4,
  99401. contrast: 1.66,
  99402. toneMappingEnabled: true
  99403. }
  99404. }
  99405. };
  99406. /***/ }),
  99407. /* 30 */
  99408. /***/ (function(module, exports) {
  99409. 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>";
  99410. /***/ }),
  99411. /* 31 */
  99412. /***/ (function(module, exports) {
  99413. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  99414. /***/ }),
  99415. /* 32 */
  99416. /***/ (function(module, exports) {
  99417. module.exports = "HELP";
  99418. /***/ }),
  99419. /* 33 */
  99420. /***/ (function(module, exports) {
  99421. module.exports = "SHARE";
  99422. /***/ }),
  99423. /* 34 */
  99424. /***/ (function(module, exports, __webpack_require__) {
  99425. (function universalModuleDefinition(root, factory) {
  99426. var amdDependencies = [];
  99427. var BABYLON = root.BABYLON || this.BABYLON;
  99428. if(true) {
  99429. BABYLON = BABYLON || __webpack_require__(0);
  99430. module.exports = factory(BABYLON);
  99431. } else if(typeof define === 'function' && define.amd) {
  99432. amdDependencies.push("babylonjs");
  99433. define("babylonjs-loaders", amdDependencies, factory);
  99434. } else if(typeof exports === 'object') {
  99435. BABYLON = BABYLON || require("babylonjs");
  99436. exports["babylonjs-loaders"] = factory(BABYLON);
  99437. } else {
  99438. root["BABYLON"] = factory(BABYLON);
  99439. }
  99440. })(this, function(BABYLON) {
  99441. BABYLON = BABYLON || this.BABYLON;
  99442. 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};
  99443. 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)}}();
  99444. "use strict";
  99445. var BABYLON;
  99446. (function (BABYLON) {
  99447. var STLFileLoader = /** @class */ (function () {
  99448. function STLFileLoader() {
  99449. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  99450. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  99451. 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;
  99452. 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;
  99453. this.name = "stl";
  99454. // force data to come in as an ArrayBuffer
  99455. // we'll convert to string if it looks like it's an ASCII .stl
  99456. this.extensions = {
  99457. ".stl": { isBinary: true },
  99458. };
  99459. }
  99460. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  99461. var matches;
  99462. if (this.isBinary(data)) {
  99463. // binary .stl
  99464. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  99465. this.parseBinary(babylonMesh, data);
  99466. if (meshes) {
  99467. meshes.push(babylonMesh);
  99468. }
  99469. return true;
  99470. }
  99471. // ASCII .stl
  99472. // convert to string
  99473. var array_buffer = new Uint8Array(data);
  99474. var str = '';
  99475. for (var i = 0; i < data.byteLength; i++) {
  99476. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  99477. }
  99478. data = str;
  99479. while (matches = this.solidPattern.exec(data)) {
  99480. var meshName = matches[1];
  99481. var meshNameFromEnd = matches[3];
  99482. if (meshName != meshNameFromEnd) {
  99483. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  99484. return false;
  99485. }
  99486. // check meshesNames
  99487. if (meshesNames && meshName) {
  99488. if (meshesNames instanceof Array) {
  99489. if (!meshesNames.indexOf(meshName)) {
  99490. continue;
  99491. }
  99492. }
  99493. else {
  99494. if (meshName !== meshesNames) {
  99495. continue;
  99496. }
  99497. }
  99498. }
  99499. // stl mesh name can be empty as well
  99500. meshName = meshName || "stlmesh";
  99501. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  99502. this.parseASCII(babylonMesh, matches[2]);
  99503. if (meshes) {
  99504. meshes.push(babylonMesh);
  99505. }
  99506. }
  99507. return true;
  99508. };
  99509. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  99510. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  99511. if (result) {
  99512. scene.createDefaultCameraOrLight();
  99513. }
  99514. return result;
  99515. };
  99516. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  99517. var container = new BABYLON.AssetContainer(scene);
  99518. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  99519. container.removeAllFromScene();
  99520. return container;
  99521. };
  99522. STLFileLoader.prototype.isBinary = function (data) {
  99523. // check if file size is correct for binary stl
  99524. var faceSize, nFaces, reader;
  99525. reader = new DataView(data);
  99526. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  99527. nFaces = reader.getUint32(80, true);
  99528. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  99529. return true;
  99530. }
  99531. // check characters higher than ASCII to confirm binary
  99532. var fileLength = reader.byteLength;
  99533. for (var index = 0; index < fileLength; index++) {
  99534. if (reader.getUint8(index) > 127) {
  99535. return true;
  99536. }
  99537. }
  99538. return false;
  99539. };
  99540. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  99541. var reader = new DataView(data);
  99542. var faces = reader.getUint32(80, true);
  99543. var dataOffset = 84;
  99544. var faceLength = 12 * 4 + 2;
  99545. var offset = 0;
  99546. var positions = new Float32Array(faces * 3 * 3);
  99547. var normals = new Float32Array(faces * 3 * 3);
  99548. var indices = new Uint32Array(faces * 3);
  99549. var indicesCount = 0;
  99550. for (var face = 0; face < faces; face++) {
  99551. var start = dataOffset + face * faceLength;
  99552. var normalX = reader.getFloat32(start, true);
  99553. var normalY = reader.getFloat32(start + 4, true);
  99554. var normalZ = reader.getFloat32(start + 8, true);
  99555. for (var i = 1; i <= 3; i++) {
  99556. var vertexstart = start + i * 12;
  99557. // ordering is intentional to match ascii import
  99558. positions[offset] = reader.getFloat32(vertexstart, true);
  99559. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  99560. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  99561. normals[offset] = normalX;
  99562. normals[offset + 2] = normalY;
  99563. normals[offset + 1] = normalZ;
  99564. offset += 3;
  99565. }
  99566. indices[indicesCount] = indicesCount++;
  99567. indices[indicesCount] = indicesCount++;
  99568. indices[indicesCount] = indicesCount++;
  99569. }
  99570. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  99571. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  99572. mesh.setIndices(indices);
  99573. mesh.computeWorldMatrix(true);
  99574. };
  99575. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  99576. var positions = [];
  99577. var normals = [];
  99578. var indices = [];
  99579. var indicesCount = 0;
  99580. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  99581. var matches;
  99582. while (matches = this.facetsPattern.exec(solidData)) {
  99583. var facet = matches[1];
  99584. //one normal per face
  99585. var normalMatches = this.normalPattern.exec(facet);
  99586. this.normalPattern.lastIndex = 0;
  99587. if (!normalMatches) {
  99588. continue;
  99589. }
  99590. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  99591. var vertexMatch;
  99592. while (vertexMatch = this.vertexPattern.exec(facet)) {
  99593. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  99594. normals.push(normal[0], normal[1], normal[2]);
  99595. }
  99596. indices.push(indicesCount++, indicesCount++, indicesCount++);
  99597. this.vertexPattern.lastIndex = 0;
  99598. }
  99599. this.facetsPattern.lastIndex = 0;
  99600. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  99601. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  99602. mesh.setIndices(indices);
  99603. mesh.computeWorldMatrix(true);
  99604. };
  99605. return STLFileLoader;
  99606. }());
  99607. BABYLON.STLFileLoader = STLFileLoader;
  99608. if (BABYLON.SceneLoader) {
  99609. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  99610. }
  99611. })(BABYLON || (BABYLON = {}));
  99612. //# sourceMappingURL=babylon.stlFileLoader.js.map
  99613. "use strict";
  99614. var BABYLON;
  99615. (function (BABYLON) {
  99616. /**
  99617. * Class reading and parsing the MTL file bundled with the obj file.
  99618. */
  99619. var MTLFileLoader = /** @class */ (function () {
  99620. function MTLFileLoader() {
  99621. // All material loaded from the mtl will be set here
  99622. this.materials = [];
  99623. }
  99624. /**
  99625. * This function will read the mtl file and create each material described inside
  99626. * This function could be improve by adding :
  99627. * -some component missing (Ni, Tf...)
  99628. * -including the specific options available
  99629. *
  99630. * @param scene
  99631. * @param data
  99632. * @param rootUrl
  99633. */
  99634. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  99635. if (data instanceof ArrayBuffer) {
  99636. return;
  99637. }
  99638. //Split the lines from the file
  99639. var lines = data.split('\n');
  99640. //Space char
  99641. var delimiter_pattern = /\s+/;
  99642. //Array with RGB colors
  99643. var color;
  99644. //New material
  99645. var material = null;
  99646. //Look at each line
  99647. for (var i = 0; i < lines.length; i++) {
  99648. var line = lines[i].trim();
  99649. // Blank line or comment
  99650. if (line.length === 0 || line.charAt(0) === '#') {
  99651. continue;
  99652. }
  99653. //Get the first parameter (keyword)
  99654. var pos = line.indexOf(' ');
  99655. var key = (pos >= 0) ? line.substring(0, pos) : line;
  99656. key = key.toLowerCase();
  99657. //Get the data following the key
  99658. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  99659. //This mtl keyword will create the new material
  99660. if (key === "newmtl") {
  99661. //Check if it is the first material.
  99662. // Materials specifications are described after this keyword.
  99663. if (material) {
  99664. //Add the previous material in the material array.
  99665. this.materials.push(material);
  99666. }
  99667. //Create a new material.
  99668. // value is the name of the material read in the mtl file
  99669. material = new BABYLON.StandardMaterial(value, scene);
  99670. }
  99671. else if (key === "kd" && material) {
  99672. // Diffuse color (color under white light) using RGB values
  99673. //value = "r g b"
  99674. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99675. //color = [r,g,b]
  99676. //Set tghe color into the material
  99677. material.diffuseColor = BABYLON.Color3.FromArray(color);
  99678. }
  99679. else if (key === "ka" && material) {
  99680. // Ambient color (color under shadow) using RGB values
  99681. //value = "r g b"
  99682. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99683. //color = [r,g,b]
  99684. //Set tghe color into the material
  99685. material.ambientColor = BABYLON.Color3.FromArray(color);
  99686. }
  99687. else if (key === "ks" && material) {
  99688. // Specular color (color when light is reflected from shiny surface) using RGB values
  99689. //value = "r g b"
  99690. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99691. //color = [r,g,b]
  99692. //Set the color into the material
  99693. material.specularColor = BABYLON.Color3.FromArray(color);
  99694. }
  99695. else if (key === "ke" && material) {
  99696. // Emissive color using RGB values
  99697. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99698. material.emissiveColor = BABYLON.Color3.FromArray(color);
  99699. }
  99700. else if (key === "ns" && material) {
  99701. //value = "Integer"
  99702. material.specularPower = parseFloat(value);
  99703. }
  99704. else if (key === "d" && material) {
  99705. //d is dissolve for current material. It mean alpha for BABYLON
  99706. material.alpha = parseFloat(value);
  99707. //Texture
  99708. //This part can be improved by adding the possible options of texture
  99709. }
  99710. else if (key === "map_ka" && material) {
  99711. // ambient texture map with a loaded image
  99712. //We must first get the folder of the image
  99713. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99714. }
  99715. else if (key === "map_kd" && material) {
  99716. // Diffuse texture map with a loaded image
  99717. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99718. }
  99719. else if (key === "map_ks" && material) {
  99720. // Specular texture map with a loaded image
  99721. //We must first get the folder of the image
  99722. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99723. }
  99724. else if (key === "map_ns") {
  99725. //Specular
  99726. //Specular highlight component
  99727. //We must first get the folder of the image
  99728. //
  99729. //Not supported by BABYLON
  99730. //
  99731. // continue;
  99732. }
  99733. else if (key === "map_bump" && material) {
  99734. //The bump texture
  99735. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99736. }
  99737. else if (key === "map_d" && material) {
  99738. // The dissolve of the material
  99739. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99740. //Options for illumination
  99741. }
  99742. else if (key === "illum") {
  99743. //Illumination
  99744. if (value === "0") {
  99745. //That mean Kd == Kd
  99746. }
  99747. else if (value === "1") {
  99748. //Color on and Ambient on
  99749. }
  99750. else if (value === "2") {
  99751. //Highlight on
  99752. }
  99753. else if (value === "3") {
  99754. //Reflection on and Ray trace on
  99755. }
  99756. else if (value === "4") {
  99757. //Transparency: Glass on, Reflection: Ray trace on
  99758. }
  99759. else if (value === "5") {
  99760. //Reflection: Fresnel on and Ray trace on
  99761. }
  99762. else if (value === "6") {
  99763. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  99764. }
  99765. else if (value === "7") {
  99766. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  99767. }
  99768. else if (value === "8") {
  99769. //Reflection on and Ray trace off
  99770. }
  99771. else if (value === "9") {
  99772. //Transparency: Glass on, Reflection: Ray trace off
  99773. }
  99774. else if (value === "10") {
  99775. //Casts shadows onto invisible surfaces
  99776. }
  99777. }
  99778. else {
  99779. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  99780. }
  99781. }
  99782. //At the end of the file, add the last material
  99783. if (material) {
  99784. this.materials.push(material);
  99785. }
  99786. };
  99787. /**
  99788. * Gets the texture for the material.
  99789. *
  99790. * If the material is imported from input file,
  99791. * We sanitize the url to ensure it takes the textre from aside the material.
  99792. *
  99793. * @param rootUrl The root url to load from
  99794. * @param value The value stored in the mtl
  99795. * @return The Texture
  99796. */
  99797. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  99798. if (!value) {
  99799. return null;
  99800. }
  99801. var url = rootUrl;
  99802. // Load from input file.
  99803. if (rootUrl === "file:") {
  99804. var lastDelimiter = value.lastIndexOf("\\");
  99805. if (lastDelimiter === -1) {
  99806. lastDelimiter = value.lastIndexOf("/");
  99807. }
  99808. if (lastDelimiter > -1) {
  99809. url += value.substr(lastDelimiter + 1);
  99810. }
  99811. else {
  99812. url += value;
  99813. }
  99814. }
  99815. else {
  99816. url += value;
  99817. }
  99818. return new BABYLON.Texture(url, scene);
  99819. };
  99820. return MTLFileLoader;
  99821. }());
  99822. BABYLON.MTLFileLoader = MTLFileLoader;
  99823. var OBJFileLoader = /** @class */ (function () {
  99824. function OBJFileLoader() {
  99825. this.name = "obj";
  99826. this.extensions = ".obj";
  99827. this.obj = /^o/;
  99828. this.group = /^g/;
  99829. this.mtllib = /^mtllib /;
  99830. this.usemtl = /^usemtl /;
  99831. this.smooth = /^s /;
  99832. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99833. // vn float float float
  99834. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99835. // vt float float
  99836. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99837. // f vertex vertex vertex ...
  99838. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  99839. // f vertex/uvs vertex/uvs vertex/uvs ...
  99840. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  99841. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  99842. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  99843. // f vertex//normal vertex//normal vertex//normal ...
  99844. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  99845. }
  99846. /**
  99847. * Calls synchronously the MTL file attached to this obj.
  99848. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  99849. * Without this function materials are not displayed in the first frame (but displayed after).
  99850. * In consequence it is impossible to get material information in your HTML file
  99851. *
  99852. * @param url The URL of the MTL file
  99853. * @param rootUrl
  99854. * @param onSuccess Callback function to be called when the MTL file is loaded
  99855. * @private
  99856. */
  99857. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  99858. //The complete path to the mtl file
  99859. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  99860. // Loads through the babylon tools to allow fileInput search.
  99861. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  99862. };
  99863. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  99864. //get the meshes from OBJ file
  99865. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  99866. //Push meshes from OBJ file into the variable mesh of this function
  99867. if (meshes) {
  99868. loadedMeshes.forEach(function (mesh) {
  99869. meshes.push(mesh);
  99870. });
  99871. }
  99872. return true;
  99873. };
  99874. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  99875. //Get the 3D model
  99876. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  99877. };
  99878. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  99879. var container = new BABYLON.AssetContainer(scene);
  99880. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  99881. container.removeAllFromScene();
  99882. return container;
  99883. };
  99884. /**
  99885. * Read the OBJ file and create an Array of meshes.
  99886. * Each mesh contains all information given by the OBJ and the MTL file.
  99887. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  99888. *
  99889. * @param meshesNames
  99890. * @param scene BABYLON.Scene The scene where are displayed the data
  99891. * @param data String The content of the obj file
  99892. * @param rootUrl String The path to the folder
  99893. * @returns Array<AbstractMesh>
  99894. * @private
  99895. */
  99896. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  99897. var positions = []; //values for the positions of vertices
  99898. var normals = []; //Values for the normals
  99899. var uvs = []; //Values for the textures
  99900. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  99901. var handledMesh; //The current mesh of meshes array
  99902. var indicesForBabylon = []; //The list of indices for VertexData
  99903. var wrappedPositionForBabylon = []; //The list of position in vectors
  99904. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  99905. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  99906. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  99907. var curPositionInIndices = 0;
  99908. var hasMeshes = false; //Meshes are defined in the file
  99909. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  99910. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  99911. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  99912. var triangles = []; //Indices from new triangles coming from polygons
  99913. var materialNameFromObj = ""; //The name of the current material
  99914. var fileToLoad = ""; //The name of the mtlFile to load
  99915. var materialsFromMTLFile = new MTLFileLoader();
  99916. var objMeshName = ""; //The name of the current obj mesh
  99917. var increment = 1; //Id for meshes created by the multimaterial
  99918. var isFirstMaterial = true;
  99919. /**
  99920. * Search for obj in the given array.
  99921. * This function is called to check if a couple of data already exists in an array.
  99922. *
  99923. * If found, returns the index of the founded tuple index. Returns -1 if not found
  99924. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  99925. * @param obj Array<number>
  99926. * @returns {boolean}
  99927. */
  99928. var isInArray = function (arr, obj) {
  99929. if (!arr[obj[0]])
  99930. arr[obj[0]] = { normals: [], idx: [] };
  99931. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  99932. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  99933. };
  99934. var isInArrayUV = function (arr, obj) {
  99935. if (!arr[obj[0]])
  99936. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  99937. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  99938. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  99939. return arr[obj[0]].idx[idx];
  99940. }
  99941. return -1;
  99942. };
  99943. /**
  99944. * This function set the data for each triangle.
  99945. * Data are position, normals and uvs
  99946. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  99947. * If the tuple already exist, add only their indice
  99948. *
  99949. * @param indicePositionFromObj Integer The index in positions array
  99950. * @param indiceUvsFromObj Integer The index in uvs array
  99951. * @param indiceNormalFromObj Integer The index in normals array
  99952. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  99953. * @param textureVectorFromOBJ Vector3 The value of uvs
  99954. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  99955. */
  99956. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  99957. //Check if this tuple already exists in the list of tuples
  99958. var _index;
  99959. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  99960. _index = isInArrayUV(tuplePosNorm, [
  99961. indicePositionFromObj,
  99962. indiceNormalFromObj,
  99963. indiceUvsFromObj
  99964. ]);
  99965. }
  99966. else {
  99967. _index = isInArray(tuplePosNorm, [
  99968. indicePositionFromObj,
  99969. indiceNormalFromObj
  99970. ]);
  99971. }
  99972. //If it not exists
  99973. if (_index == -1) {
  99974. //Add an new indice.
  99975. //The array of indices is only an array with his length equal to the number of triangles - 1.
  99976. //We add vertices data in this order
  99977. indicesForBabylon.push(wrappedPositionForBabylon.length);
  99978. //Push the position of vertice for Babylon
  99979. //Each element is a BABYLON.Vector3(x,y,z)
  99980. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  99981. //Push the uvs for Babylon
  99982. //Each element is a BABYLON.Vector3(u,v)
  99983. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  99984. //Push the normals for Babylon
  99985. //Each element is a BABYLON.Vector3(x,y,z)
  99986. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  99987. //Add the tuple in the comparison list
  99988. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  99989. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  99990. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  99991. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  99992. }
  99993. else {
  99994. //The tuple already exists
  99995. //Add the index of the already existing tuple
  99996. //At this index we can get the value of position, normal and uvs of vertex
  99997. indicesForBabylon.push(_index);
  99998. }
  99999. };
  100000. /**
  100001. * Transform BABYLON.Vector() object onto 3 digits in an array
  100002. */
  100003. var unwrapData = function () {
  100004. //Every array has the same length
  100005. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  100006. //Push the x, y, z values of each element in the unwrapped array
  100007. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  100008. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  100009. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  100010. }
  100011. // Reset arrays for the next new meshes
  100012. wrappedPositionForBabylon = [];
  100013. wrappedNormalsForBabylon = [];
  100014. wrappedUvsForBabylon = [];
  100015. tuplePosNorm = [];
  100016. curPositionInIndices = 0;
  100017. };
  100018. /**
  100019. * Create triangles from polygons by recursion
  100020. * The best to understand how it works is to draw it in the same time you get the recursion.
  100021. * It is important to notice that a triangle is a polygon
  100022. * We get 4 patterns of face defined in OBJ File :
  100023. * facePattern1 = ["1","2","3","4","5","6"]
  100024. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  100025. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  100026. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  100027. * Each pattern is divided by the same method
  100028. * @param face Array[String] The indices of elements
  100029. * @param v Integer The variable to increment
  100030. */
  100031. var getTriangles = function (face, v) {
  100032. //Work for each element of the array
  100033. if (v + 1 < face.length) {
  100034. //Add on the triangle variable the indexes to obtain triangles
  100035. triangles.push(face[0], face[v], face[v + 1]);
  100036. //Incrementation for recursion
  100037. v += 1;
  100038. //Recursion
  100039. getTriangles(face, v);
  100040. }
  100041. //Result obtained after 2 iterations:
  100042. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  100043. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  100044. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  100045. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  100046. };
  100047. /**
  100048. * Create triangles and push the data for each polygon for the pattern 1
  100049. * In this pattern we get vertice positions
  100050. * @param face
  100051. * @param v
  100052. */
  100053. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  100054. //Get the indices of triangles for each polygon
  100055. getTriangles(face, v);
  100056. //For each element in the triangles array.
  100057. //This var could contains 1 to an infinity of triangles
  100058. for (var k = 0; k < triangles.length; k++) {
  100059. // Set position indice
  100060. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  100061. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  100062. positions[indicePositionFromObj], //Get the vectors data
  100063. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  100064. );
  100065. }
  100066. //Reset variable for the next line
  100067. triangles = [];
  100068. };
  100069. /**
  100070. * Create triangles and push the data for each polygon for the pattern 2
  100071. * In this pattern we get vertice positions and uvsu
  100072. * @param face
  100073. * @param v
  100074. */
  100075. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  100076. //Get the indices of triangles for each polygon
  100077. getTriangles(face, v);
  100078. for (var k = 0; k < triangles.length; k++) {
  100079. //triangle[k] = "1/1"
  100080. //Split the data for getting position and uv
  100081. var point = triangles[k].split("/"); // ["1", "1"]
  100082. //Set position indice
  100083. var indicePositionFromObj = parseInt(point[0]) - 1;
  100084. //Set uv indice
  100085. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100086. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  100087. positions[indicePositionFromObj], //Get the values for each element
  100088. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  100089. );
  100090. }
  100091. //Reset variable for the next line
  100092. triangles = [];
  100093. };
  100094. /**
  100095. * Create triangles and push the data for each polygon for the pattern 3
  100096. * In this pattern we get vertice positions, uvs and normals
  100097. * @param face
  100098. * @param v
  100099. */
  100100. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  100101. //Get the indices of triangles for each polygon
  100102. getTriangles(face, v);
  100103. for (var k = 0; k < triangles.length; k++) {
  100104. //triangle[k] = "1/1/1"
  100105. //Split the data for getting position, uv, and normals
  100106. var point = triangles[k].split("/"); // ["1", "1", "1"]
  100107. // Set position indice
  100108. var indicePositionFromObj = parseInt(point[0]) - 1;
  100109. // Set uv indice
  100110. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100111. // Set normal indice
  100112. var indiceNormalFromObj = parseInt(point[2]) - 1;
  100113. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  100114. );
  100115. }
  100116. //Reset variable for the next line
  100117. triangles = [];
  100118. };
  100119. /**
  100120. * Create triangles and push the data for each polygon for the pattern 4
  100121. * In this pattern we get vertice positions and normals
  100122. * @param face
  100123. * @param v
  100124. */
  100125. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  100126. getTriangles(face, v);
  100127. for (var k = 0; k < triangles.length; k++) {
  100128. //triangle[k] = "1//1"
  100129. //Split the data for getting position and normals
  100130. var point = triangles[k].split("//"); // ["1", "1"]
  100131. // We check indices, and normals
  100132. var indicePositionFromObj = parseInt(point[0]) - 1;
  100133. var indiceNormalFromObj = parseInt(point[1]) - 1;
  100134. setData(indicePositionFromObj, 1, //Default value for uv
  100135. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  100136. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  100137. }
  100138. //Reset variable for the next line
  100139. triangles = [];
  100140. };
  100141. var addPreviousObjMesh = function () {
  100142. //Check if it is not the first mesh. Otherwise we don't have data.
  100143. if (meshesFromObj.length > 0) {
  100144. //Get the previous mesh for applying the data about the faces
  100145. //=> in obj file, faces definition append after the name of the mesh
  100146. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100147. //Set the data into Array for the mesh
  100148. unwrapData();
  100149. // Reverse tab. Otherwise face are displayed in the wrong sens
  100150. indicesForBabylon.reverse();
  100151. //Set the information for the mesh
  100152. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  100153. handledMesh.indices = indicesForBabylon.slice();
  100154. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  100155. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  100156. handledMesh.uvs = unwrappedUVForBabylon.slice();
  100157. //Reset the array for the next mesh
  100158. indicesForBabylon = [];
  100159. unwrappedPositionsForBabylon = [];
  100160. unwrappedNormalsForBabylon = [];
  100161. unwrappedUVForBabylon = [];
  100162. }
  100163. };
  100164. //Main function
  100165. //Split the file into lines
  100166. var lines = data.split('\n');
  100167. //Look at each line
  100168. for (var i = 0; i < lines.length; i++) {
  100169. var line = lines[i].trim();
  100170. var result;
  100171. //Comment or newLine
  100172. if (line.length === 0 || line.charAt(0) === '#') {
  100173. continue;
  100174. //Get information about one position possible for the vertices
  100175. }
  100176. else if ((result = this.vertexPattern.exec(line)) !== null) {
  100177. //Create a Vector3 with the position x, y, z
  100178. //Value of result:
  100179. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100180. //Add the Vector in the list of positions
  100181. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100182. }
  100183. else if ((result = this.normalPattern.exec(line)) !== null) {
  100184. //Create a Vector3 with the normals x, y, z
  100185. //Value of result
  100186. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100187. //Add the Vector in the list of normals
  100188. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100189. }
  100190. else if ((result = this.uvPattern.exec(line)) !== null) {
  100191. //Create a Vector2 with the normals u, v
  100192. //Value of result
  100193. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  100194. //Add the Vector in the list of uvs
  100195. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  100196. //Identify patterns of faces
  100197. //Face could be defined in different type of pattern
  100198. }
  100199. else if ((result = this.facePattern3.exec(line)) !== null) {
  100200. //Value of result:
  100201. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  100202. //Set the data for this face
  100203. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  100204. 1);
  100205. }
  100206. else if ((result = this.facePattern4.exec(line)) !== null) {
  100207. //Value of result:
  100208. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  100209. //Set the data for this face
  100210. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  100211. 1);
  100212. }
  100213. else if ((result = this.facePattern2.exec(line)) !== null) {
  100214. //Value of result:
  100215. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  100216. //Set the data for this face
  100217. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  100218. 1);
  100219. }
  100220. else if ((result = this.facePattern1.exec(line)) !== null) {
  100221. //Value of result
  100222. //["f 1 2 3", "1 2 3"...]
  100223. //Set the data for this face
  100224. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  100225. 1);
  100226. //Define a mesh or an object
  100227. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  100228. }
  100229. else if (this.group.test(line) || this.obj.test(line)) {
  100230. //Create a new mesh corresponding to the name of the group.
  100231. //Definition of the mesh
  100232. var objMesh =
  100233. //Set the name of the current obj mesh
  100234. {
  100235. name: line.substring(2).trim(),
  100236. indices: undefined,
  100237. positions: undefined,
  100238. normals: undefined,
  100239. uvs: undefined,
  100240. materialName: ""
  100241. };
  100242. addPreviousObjMesh();
  100243. //Push the last mesh created with only the name
  100244. meshesFromObj.push(objMesh);
  100245. //Set this variable to indicate that now meshesFromObj has objects defined inside
  100246. hasMeshes = true;
  100247. isFirstMaterial = true;
  100248. increment = 1;
  100249. //Keyword for applying a material
  100250. }
  100251. else if (this.usemtl.test(line)) {
  100252. //Get the name of the material
  100253. materialNameFromObj = line.substring(7).trim();
  100254. //If this new material is in the same mesh
  100255. if (!isFirstMaterial) {
  100256. //Set the data for the previous mesh
  100257. addPreviousObjMesh();
  100258. //Create a new mesh
  100259. var objMesh =
  100260. //Set the name of the current obj mesh
  100261. {
  100262. name: objMeshName + "_mm" + increment.toString(),
  100263. indices: undefined,
  100264. positions: undefined,
  100265. normals: undefined,
  100266. uvs: undefined,
  100267. materialName: materialNameFromObj
  100268. };
  100269. increment++;
  100270. //If meshes are already defined
  100271. meshesFromObj.push(objMesh);
  100272. }
  100273. //Set the material name if the previous line define a mesh
  100274. if (hasMeshes && isFirstMaterial) {
  100275. //Set the material name to the previous mesh (1 material per mesh)
  100276. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  100277. isFirstMaterial = false;
  100278. }
  100279. //Keyword for loading the mtl file
  100280. }
  100281. else if (this.mtllib.test(line)) {
  100282. //Get the name of mtl file
  100283. fileToLoad = line.substring(7).trim();
  100284. //Apply smoothing
  100285. }
  100286. else if (this.smooth.test(line)) {
  100287. // smooth shading => apply smoothing
  100288. //Toda y I don't know it work with babylon and with obj.
  100289. //With the obj file an integer is set
  100290. }
  100291. else {
  100292. //If there is another possibility
  100293. console.log("Unhandled expression at line : " + line);
  100294. }
  100295. }
  100296. //At the end of the file, add the last mesh into the meshesFromObj array
  100297. if (hasMeshes) {
  100298. //Set the data for the last mesh
  100299. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100300. //Reverse indices for displaying faces in the good sens
  100301. indicesForBabylon.reverse();
  100302. //Get the good array
  100303. unwrapData();
  100304. //Set array
  100305. handledMesh.indices = indicesForBabylon;
  100306. handledMesh.positions = unwrappedPositionsForBabylon;
  100307. handledMesh.normals = unwrappedNormalsForBabylon;
  100308. handledMesh.uvs = unwrappedUVForBabylon;
  100309. }
  100310. //If any o or g keyword found, create a mesj with a random id
  100311. if (!hasMeshes) {
  100312. // reverse tab of indices
  100313. indicesForBabylon.reverse();
  100314. //Get positions normals uvs
  100315. unwrapData();
  100316. //Set data for one mesh
  100317. meshesFromObj.push({
  100318. name: BABYLON.Geometry.RandomId(),
  100319. indices: indicesForBabylon,
  100320. positions: unwrappedPositionsForBabylon,
  100321. normals: unwrappedNormalsForBabylon,
  100322. uvs: unwrappedUVForBabylon,
  100323. materialName: materialNameFromObj
  100324. });
  100325. }
  100326. //Create a BABYLON.Mesh list
  100327. var babylonMeshesArray = []; //The mesh for babylon
  100328. var materialToUse = new Array();
  100329. //Set data for each mesh
  100330. for (var j = 0; j < meshesFromObj.length; j++) {
  100331. //check meshesNames (stlFileLoader)
  100332. if (meshesNames && meshesFromObj[j].name) {
  100333. if (meshesNames instanceof Array) {
  100334. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  100335. continue;
  100336. }
  100337. }
  100338. else {
  100339. if (meshesFromObj[j].name !== meshesNames) {
  100340. continue;
  100341. }
  100342. }
  100343. }
  100344. //Get the current mesh
  100345. //Set the data with VertexBuffer for each mesh
  100346. handledMesh = meshesFromObj[j];
  100347. //Create a BABYLON.Mesh with the name of the obj mesh
  100348. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  100349. //Push the name of the material to an array
  100350. //This is indispensable for the importMesh function
  100351. materialToUse.push(meshesFromObj[j].materialName);
  100352. var vertexData = new BABYLON.VertexData(); //The container for the values
  100353. //Set the data for the babylonMesh
  100354. vertexData.positions = handledMesh.positions;
  100355. vertexData.normals = handledMesh.normals;
  100356. vertexData.uvs = handledMesh.uvs;
  100357. vertexData.indices = handledMesh.indices;
  100358. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  100359. vertexData.applyToMesh(babylonMesh);
  100360. //Push the mesh into an array
  100361. babylonMeshesArray.push(babylonMesh);
  100362. }
  100363. //load the materials
  100364. //Check if we have a file to load
  100365. if (fileToLoad !== "") {
  100366. //Load the file synchronously
  100367. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  100368. //Create materials thanks MTLLoader function
  100369. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  100370. //Look at each material loaded in the mtl file
  100371. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  100372. //Three variables to get all meshes with the same material
  100373. var startIndex = 0;
  100374. var _indices = [];
  100375. var _index;
  100376. //The material from MTL file is used in the meshes loaded
  100377. //Push the indice in an array
  100378. //Check if the material is not used for another mesh
  100379. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  100380. _indices.push(_index);
  100381. startIndex = _index + 1;
  100382. }
  100383. //If the material is not used dispose it
  100384. if (_index == -1 && _indices.length == 0) {
  100385. //If the material is not needed, remove it
  100386. materialsFromMTLFile.materials[n].dispose();
  100387. }
  100388. else {
  100389. for (var o = 0; o < _indices.length; o++) {
  100390. //Apply the material to the BABYLON.Mesh for each mesh with the material
  100391. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  100392. }
  100393. }
  100394. }
  100395. });
  100396. }
  100397. //Return an array with all BABYLON.Mesh
  100398. return babylonMeshesArray;
  100399. };
  100400. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  100401. return OBJFileLoader;
  100402. }());
  100403. BABYLON.OBJFileLoader = OBJFileLoader;
  100404. if (BABYLON.SceneLoader) {
  100405. //Add this loader into the register plugin
  100406. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  100407. }
  100408. })(BABYLON || (BABYLON = {}));
  100409. //# sourceMappingURL=babylon.objFileLoader.js.map
  100410. "use strict";
  100411. var BABYLON;
  100412. (function (BABYLON) {
  100413. var GLTFLoaderCoordinateSystemMode;
  100414. (function (GLTFLoaderCoordinateSystemMode) {
  100415. /**
  100416. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  100417. */
  100418. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  100419. /**
  100420. * Sets the useRightHandedSystem flag on the scene.
  100421. */
  100422. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  100423. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  100424. var GLTFLoaderAnimationStartMode;
  100425. (function (GLTFLoaderAnimationStartMode) {
  100426. /**
  100427. * No animation will start.
  100428. */
  100429. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  100430. /**
  100431. * The first animation will start.
  100432. */
  100433. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  100434. /**
  100435. * All animations will start.
  100436. */
  100437. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  100438. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  100439. var GLTFLoaderState;
  100440. (function (GLTFLoaderState) {
  100441. /**
  100442. * The asset is loading.
  100443. */
  100444. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  100445. /**
  100446. * The asset is ready for rendering.
  100447. */
  100448. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  100449. /**
  100450. * The asset is completely loaded.
  100451. */
  100452. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  100453. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  100454. var GLTFFileLoader = /** @class */ (function () {
  100455. function GLTFFileLoader() {
  100456. // #region Common options
  100457. /**
  100458. * Raised when the asset has been parsed.
  100459. * The data.json property stores the glTF JSON.
  100460. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  100461. */
  100462. this.onParsedObservable = new BABYLON.Observable();
  100463. // #endregion
  100464. // #region V2 options
  100465. /**
  100466. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  100467. */
  100468. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  100469. /**
  100470. * The animation start mode (NONE, FIRST, ALL).
  100471. */
  100472. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  100473. /**
  100474. * Set to true to compile materials before raising the success callback.
  100475. */
  100476. this.compileMaterials = false;
  100477. /**
  100478. * Set to true to also compile materials with clip planes.
  100479. */
  100480. this.useClipPlane = false;
  100481. /**
  100482. * Set to true to compile shadow generators before raising the success callback.
  100483. */
  100484. this.compileShadowGenerators = false;
  100485. /**
  100486. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  100487. */
  100488. this.onMeshLoadedObservable = new BABYLON.Observable();
  100489. /**
  100490. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  100491. */
  100492. this.onTextureLoadedObservable = new BABYLON.Observable();
  100493. /**
  100494. * Raised when the loader creates a material after parsing the glTF properties of the material.
  100495. */
  100496. this.onMaterialLoadedObservable = new BABYLON.Observable();
  100497. /**
  100498. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  100499. * For assets with LODs, raised when all of the LODs are complete.
  100500. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  100501. */
  100502. this.onCompleteObservable = new BABYLON.Observable();
  100503. /**
  100504. * Raised after the loader is disposed.
  100505. */
  100506. this.onDisposeObservable = new BABYLON.Observable();
  100507. /**
  100508. * Raised after a loader extension is created.
  100509. * Set additional options for a loader extension in this event.
  100510. */
  100511. this.onExtensionLoadedObservable = new BABYLON.Observable();
  100512. // #endregion
  100513. this._loader = null;
  100514. this.name = "gltf";
  100515. this.extensions = {
  100516. ".gltf": { isBinary: false },
  100517. ".glb": { isBinary: true }
  100518. };
  100519. }
  100520. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  100521. set: function (callback) {
  100522. if (this._onParsedObserver) {
  100523. this.onParsedObservable.remove(this._onParsedObserver);
  100524. }
  100525. this._onParsedObserver = this.onParsedObservable.add(callback);
  100526. },
  100527. enumerable: true,
  100528. configurable: true
  100529. });
  100530. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  100531. set: function (callback) {
  100532. if (this._onMeshLoadedObserver) {
  100533. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  100534. }
  100535. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  100536. },
  100537. enumerable: true,
  100538. configurable: true
  100539. });
  100540. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  100541. set: function (callback) {
  100542. if (this._onTextureLoadedObserver) {
  100543. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  100544. }
  100545. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  100546. },
  100547. enumerable: true,
  100548. configurable: true
  100549. });
  100550. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  100551. set: function (callback) {
  100552. if (this._onMaterialLoadedObserver) {
  100553. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  100554. }
  100555. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  100556. },
  100557. enumerable: true,
  100558. configurable: true
  100559. });
  100560. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  100561. set: function (callback) {
  100562. if (this._onCompleteObserver) {
  100563. this.onCompleteObservable.remove(this._onCompleteObserver);
  100564. }
  100565. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  100566. },
  100567. enumerable: true,
  100568. configurable: true
  100569. });
  100570. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  100571. set: function (callback) {
  100572. if (this._onDisposeObserver) {
  100573. this.onDisposeObservable.remove(this._onDisposeObserver);
  100574. }
  100575. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100576. },
  100577. enumerable: true,
  100578. configurable: true
  100579. });
  100580. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  100581. set: function (callback) {
  100582. if (this._onExtensionLoadedObserver) {
  100583. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  100584. }
  100585. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  100586. },
  100587. enumerable: true,
  100588. configurable: true
  100589. });
  100590. /**
  100591. * Returns a promise that resolves when the asset is completely loaded.
  100592. * @returns A promise that resolves when the asset is completely loaded.
  100593. */
  100594. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  100595. var _this = this;
  100596. return new Promise(function (resolve) {
  100597. _this.onCompleteObservable.add(function () {
  100598. resolve();
  100599. }, undefined, undefined, undefined, true);
  100600. });
  100601. };
  100602. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  100603. /**
  100604. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  100605. */
  100606. get: function () {
  100607. return this._loader ? this._loader.state : null;
  100608. },
  100609. enumerable: true,
  100610. configurable: true
  100611. });
  100612. /**
  100613. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  100614. */
  100615. GLTFFileLoader.prototype.dispose = function () {
  100616. if (this._loader) {
  100617. this._loader.dispose();
  100618. this._loader = null;
  100619. }
  100620. this.onMeshLoadedObservable.clear();
  100621. this.onTextureLoadedObservable.clear();
  100622. this.onMaterialLoadedObservable.clear();
  100623. this.onDisposeObservable.notifyObservers(this);
  100624. this.onDisposeObservable.clear();
  100625. };
  100626. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  100627. var _this = this;
  100628. return Promise.resolve().then(function () {
  100629. var loaderData = _this._parse(data);
  100630. _this._loader = _this._getLoader(loaderData);
  100631. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  100632. });
  100633. };
  100634. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  100635. var _this = this;
  100636. return Promise.resolve().then(function () {
  100637. var loaderData = _this._parse(data);
  100638. _this._loader = _this._getLoader(loaderData);
  100639. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  100640. });
  100641. };
  100642. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  100643. var _this = this;
  100644. return Promise.resolve().then(function () {
  100645. var loaderData = _this._parse(data);
  100646. _this._loader = _this._getLoader(loaderData);
  100647. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  100648. var container = new BABYLON.AssetContainer(scene);
  100649. Array.prototype.push.apply(container.meshes, result.meshes);
  100650. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  100651. Array.prototype.push.apply(container.skeletons, result.skeletons);
  100652. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  100653. container.removeAllFromScene();
  100654. return container;
  100655. });
  100656. });
  100657. };
  100658. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  100659. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  100660. };
  100661. GLTFFileLoader.prototype.createPlugin = function () {
  100662. return new GLTFFileLoader();
  100663. };
  100664. GLTFFileLoader.prototype._parse = function (data) {
  100665. var parsedData;
  100666. if (data instanceof ArrayBuffer) {
  100667. parsedData = GLTFFileLoader._parseBinary(data);
  100668. }
  100669. else {
  100670. parsedData = {
  100671. json: JSON.parse(data),
  100672. bin: null
  100673. };
  100674. }
  100675. this.onParsedObservable.notifyObservers(parsedData);
  100676. this.onParsedObservable.clear();
  100677. return parsedData;
  100678. };
  100679. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  100680. var _this = this;
  100681. var loaderVersion = { major: 2, minor: 0 };
  100682. var asset = loaderData.json.asset || {};
  100683. var version = GLTFFileLoader._parseVersion(asset.version);
  100684. if (!version) {
  100685. throw new Error("Invalid version: " + asset.version);
  100686. }
  100687. if (asset.minVersion !== undefined) {
  100688. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  100689. if (!minVersion) {
  100690. throw new Error("Invalid minimum version: " + asset.minVersion);
  100691. }
  100692. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  100693. throw new Error("Incompatible minimum version: " + asset.minVersion);
  100694. }
  100695. }
  100696. var createLoaders = {
  100697. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  100698. 2: GLTFFileLoader.CreateGLTFLoaderV2
  100699. };
  100700. var createLoader = createLoaders[version.major];
  100701. if (!createLoader) {
  100702. throw new Error("Unsupported version: " + asset.version);
  100703. }
  100704. var loader = createLoader();
  100705. loader.coordinateSystemMode = this.coordinateSystemMode;
  100706. loader.animationStartMode = this.animationStartMode;
  100707. loader.compileMaterials = this.compileMaterials;
  100708. loader.useClipPlane = this.useClipPlane;
  100709. loader.compileShadowGenerators = this.compileShadowGenerators;
  100710. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  100711. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  100712. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  100713. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  100714. loader.onCompleteObservable.add(function () {
  100715. _this.onMeshLoadedObservable.clear();
  100716. _this.onTextureLoadedObservable.clear();
  100717. _this.onMaterialLoadedObservable.clear();
  100718. _this.onCompleteObservable.notifyObservers(_this);
  100719. _this.onCompleteObservable.clear();
  100720. });
  100721. return loader;
  100722. };
  100723. GLTFFileLoader._parseBinary = function (data) {
  100724. var Binary = {
  100725. Magic: 0x46546C67
  100726. };
  100727. var binaryReader = new BinaryReader(data);
  100728. var magic = binaryReader.readUint32();
  100729. if (magic !== Binary.Magic) {
  100730. throw new Error("Unexpected magic: " + magic);
  100731. }
  100732. var version = binaryReader.readUint32();
  100733. switch (version) {
  100734. case 1: return GLTFFileLoader._parseV1(binaryReader);
  100735. case 2: return GLTFFileLoader._parseV2(binaryReader);
  100736. }
  100737. throw new Error("Unsupported version: " + version);
  100738. };
  100739. GLTFFileLoader._parseV1 = function (binaryReader) {
  100740. var ContentFormat = {
  100741. JSON: 0
  100742. };
  100743. var length = binaryReader.readUint32();
  100744. if (length != binaryReader.getLength()) {
  100745. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  100746. }
  100747. var contentLength = binaryReader.readUint32();
  100748. var contentFormat = binaryReader.readUint32();
  100749. var content;
  100750. switch (contentFormat) {
  100751. case ContentFormat.JSON: {
  100752. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  100753. break;
  100754. }
  100755. default: {
  100756. throw new Error("Unexpected content format: " + contentFormat);
  100757. }
  100758. }
  100759. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  100760. var body = binaryReader.readUint8Array(bytesRemaining);
  100761. return {
  100762. json: content,
  100763. bin: body
  100764. };
  100765. };
  100766. GLTFFileLoader._parseV2 = function (binaryReader) {
  100767. var ChunkFormat = {
  100768. JSON: 0x4E4F534A,
  100769. BIN: 0x004E4942
  100770. };
  100771. var length = binaryReader.readUint32();
  100772. if (length !== binaryReader.getLength()) {
  100773. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  100774. }
  100775. // JSON chunk
  100776. var chunkLength = binaryReader.readUint32();
  100777. var chunkFormat = binaryReader.readUint32();
  100778. if (chunkFormat !== ChunkFormat.JSON) {
  100779. throw new Error("First chunk format is not JSON");
  100780. }
  100781. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  100782. // Look for BIN chunk
  100783. var bin = null;
  100784. while (binaryReader.getPosition() < binaryReader.getLength()) {
  100785. var chunkLength_1 = binaryReader.readUint32();
  100786. var chunkFormat_1 = binaryReader.readUint32();
  100787. switch (chunkFormat_1) {
  100788. case ChunkFormat.JSON: {
  100789. throw new Error("Unexpected JSON chunk");
  100790. }
  100791. case ChunkFormat.BIN: {
  100792. bin = binaryReader.readUint8Array(chunkLength_1);
  100793. break;
  100794. }
  100795. default: {
  100796. // ignore unrecognized chunkFormat
  100797. binaryReader.skipBytes(chunkLength_1);
  100798. break;
  100799. }
  100800. }
  100801. }
  100802. return {
  100803. json: json,
  100804. bin: bin
  100805. };
  100806. };
  100807. GLTFFileLoader._parseVersion = function (version) {
  100808. if (version === "1.0" || version === "1.0.1") {
  100809. return {
  100810. major: 1,
  100811. minor: 0
  100812. };
  100813. }
  100814. var match = (version + "").match(/^(\d+)\.(\d+)/);
  100815. if (!match) {
  100816. return null;
  100817. }
  100818. return {
  100819. major: parseInt(match[1]),
  100820. minor: parseInt(match[2])
  100821. };
  100822. };
  100823. GLTFFileLoader._compareVersion = function (a, b) {
  100824. if (a.major > b.major)
  100825. return 1;
  100826. if (a.major < b.major)
  100827. return -1;
  100828. if (a.minor > b.minor)
  100829. return 1;
  100830. if (a.minor < b.minor)
  100831. return -1;
  100832. return 0;
  100833. };
  100834. GLTFFileLoader._decodeBufferToText = function (buffer) {
  100835. var result = "";
  100836. var length = buffer.byteLength;
  100837. for (var i = 0; i < length; i++) {
  100838. result += String.fromCharCode(buffer[i]);
  100839. }
  100840. return result;
  100841. };
  100842. // #endregion
  100843. // #region V1 options
  100844. GLTFFileLoader.IncrementalLoading = true;
  100845. GLTFFileLoader.HomogeneousCoordinates = false;
  100846. return GLTFFileLoader;
  100847. }());
  100848. BABYLON.GLTFFileLoader = GLTFFileLoader;
  100849. var BinaryReader = /** @class */ (function () {
  100850. function BinaryReader(arrayBuffer) {
  100851. this._arrayBuffer = arrayBuffer;
  100852. this._dataView = new DataView(arrayBuffer);
  100853. this._byteOffset = 0;
  100854. }
  100855. BinaryReader.prototype.getPosition = function () {
  100856. return this._byteOffset;
  100857. };
  100858. BinaryReader.prototype.getLength = function () {
  100859. return this._arrayBuffer.byteLength;
  100860. };
  100861. BinaryReader.prototype.readUint32 = function () {
  100862. var value = this._dataView.getUint32(this._byteOffset, true);
  100863. this._byteOffset += 4;
  100864. return value;
  100865. };
  100866. BinaryReader.prototype.readUint8Array = function (length) {
  100867. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  100868. this._byteOffset += length;
  100869. return value;
  100870. };
  100871. BinaryReader.prototype.skipBytes = function (length) {
  100872. this._byteOffset += length;
  100873. };
  100874. return BinaryReader;
  100875. }());
  100876. if (BABYLON.SceneLoader) {
  100877. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  100878. }
  100879. })(BABYLON || (BABYLON = {}));
  100880. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  100881. "use strict";
  100882. var BABYLON;
  100883. (function (BABYLON) {
  100884. var GLTF1;
  100885. (function (GLTF1) {
  100886. /**
  100887. * Enums
  100888. */
  100889. var EComponentType;
  100890. (function (EComponentType) {
  100891. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  100892. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  100893. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  100894. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  100895. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  100896. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  100897. var EShaderType;
  100898. (function (EShaderType) {
  100899. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  100900. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  100901. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  100902. var EParameterType;
  100903. (function (EParameterType) {
  100904. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  100905. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  100906. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  100907. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  100908. EParameterType[EParameterType["INT"] = 5124] = "INT";
  100909. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  100910. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  100911. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  100912. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  100913. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  100914. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  100915. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  100916. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  100917. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  100918. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  100919. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  100920. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  100921. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  100922. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  100923. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  100924. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  100925. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  100926. var ETextureWrapMode;
  100927. (function (ETextureWrapMode) {
  100928. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  100929. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  100930. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  100931. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  100932. var ETextureFilterType;
  100933. (function (ETextureFilterType) {
  100934. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  100935. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  100936. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  100937. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  100938. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  100939. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  100940. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  100941. var ETextureFormat;
  100942. (function (ETextureFormat) {
  100943. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  100944. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  100945. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  100946. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  100947. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  100948. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  100949. var ECullingType;
  100950. (function (ECullingType) {
  100951. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  100952. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  100953. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  100954. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  100955. var EBlendingFunction;
  100956. (function (EBlendingFunction) {
  100957. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  100958. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  100959. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  100960. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  100961. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  100962. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  100963. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  100964. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  100965. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  100966. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  100967. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  100968. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  100969. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  100970. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  100971. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  100972. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  100973. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  100974. })(BABYLON || (BABYLON = {}));
  100975. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  100976. "use strict";
  100977. var BABYLON;
  100978. (function (BABYLON) {
  100979. var GLTF1;
  100980. (function (GLTF1) {
  100981. /**
  100982. * Tokenizer. Used for shaders compatibility
  100983. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  100984. */
  100985. var ETokenType;
  100986. (function (ETokenType) {
  100987. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  100988. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  100989. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  100990. })(ETokenType || (ETokenType = {}));
  100991. var Tokenizer = /** @class */ (function () {
  100992. function Tokenizer(toParse) {
  100993. this._pos = 0;
  100994. this.currentToken = ETokenType.UNKNOWN;
  100995. this.currentIdentifier = "";
  100996. this.currentString = "";
  100997. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  100998. this._toParse = toParse;
  100999. this._maxPos = toParse.length;
  101000. }
  101001. Tokenizer.prototype.getNextToken = function () {
  101002. if (this.isEnd())
  101003. return ETokenType.END_OF_INPUT;
  101004. this.currentString = this.read();
  101005. this.currentToken = ETokenType.UNKNOWN;
  101006. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  101007. this.currentToken = ETokenType.IDENTIFIER;
  101008. this.currentIdentifier = this.currentString;
  101009. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  101010. this.currentIdentifier += this.currentString;
  101011. this.forward();
  101012. }
  101013. }
  101014. return this.currentToken;
  101015. };
  101016. Tokenizer.prototype.peek = function () {
  101017. return this._toParse[this._pos];
  101018. };
  101019. Tokenizer.prototype.read = function () {
  101020. return this._toParse[this._pos++];
  101021. };
  101022. Tokenizer.prototype.forward = function () {
  101023. this._pos++;
  101024. };
  101025. Tokenizer.prototype.isEnd = function () {
  101026. return this._pos >= this._maxPos;
  101027. };
  101028. return Tokenizer;
  101029. }());
  101030. /**
  101031. * Values
  101032. */
  101033. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  101034. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  101035. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  101036. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  101037. /**
  101038. * Parse
  101039. */
  101040. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  101041. for (var buf in parsedBuffers) {
  101042. var parsedBuffer = parsedBuffers[buf];
  101043. gltfRuntime.buffers[buf] = parsedBuffer;
  101044. gltfRuntime.buffersCount++;
  101045. }
  101046. };
  101047. var parseShaders = function (parsedShaders, gltfRuntime) {
  101048. for (var sha in parsedShaders) {
  101049. var parsedShader = parsedShaders[sha];
  101050. gltfRuntime.shaders[sha] = parsedShader;
  101051. gltfRuntime.shaderscount++;
  101052. }
  101053. };
  101054. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  101055. for (var object in parsedObjects) {
  101056. var parsedObject = parsedObjects[object];
  101057. gltfRuntime[runtimeProperty][object] = parsedObject;
  101058. }
  101059. };
  101060. /**
  101061. * Utils
  101062. */
  101063. var normalizeUVs = function (buffer) {
  101064. if (!buffer) {
  101065. return;
  101066. }
  101067. for (var i = 0; i < buffer.length / 2; i++) {
  101068. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  101069. }
  101070. };
  101071. var getAttribute = function (attributeParameter) {
  101072. if (attributeParameter.semantic === "NORMAL") {
  101073. return "normal";
  101074. }
  101075. else if (attributeParameter.semantic === "POSITION") {
  101076. return "position";
  101077. }
  101078. else if (attributeParameter.semantic === "JOINT") {
  101079. return "matricesIndices";
  101080. }
  101081. else if (attributeParameter.semantic === "WEIGHT") {
  101082. return "matricesWeights";
  101083. }
  101084. else if (attributeParameter.semantic === "COLOR") {
  101085. return "color";
  101086. }
  101087. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  101088. var channel = Number(attributeParameter.semantic.split("_")[1]);
  101089. return "uv" + (channel === 0 ? "" : channel + 1);
  101090. }
  101091. return null;
  101092. };
  101093. /**
  101094. * Loads and creates animations
  101095. */
  101096. var loadAnimations = function (gltfRuntime) {
  101097. for (var anim in gltfRuntime.animations) {
  101098. var animation = gltfRuntime.animations[anim];
  101099. if (!animation.channels || !animation.samplers) {
  101100. continue;
  101101. }
  101102. var lastAnimation = null;
  101103. for (var i = 0; i < animation.channels.length; i++) {
  101104. // Get parameters and load buffers
  101105. var channel = animation.channels[i];
  101106. var sampler = animation.samplers[channel.sampler];
  101107. if (!sampler) {
  101108. continue;
  101109. }
  101110. var inputData = null;
  101111. var outputData = null;
  101112. if (animation.parameters) {
  101113. inputData = animation.parameters[sampler.input];
  101114. outputData = animation.parameters[sampler.output];
  101115. }
  101116. else {
  101117. inputData = sampler.input;
  101118. outputData = sampler.output;
  101119. }
  101120. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  101121. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  101122. var targetID = channel.target.id;
  101123. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  101124. if (targetNode === null) {
  101125. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  101126. }
  101127. if (targetNode === null) {
  101128. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  101129. continue;
  101130. }
  101131. var isBone = targetNode instanceof BABYLON.Bone;
  101132. // Get target path (position, rotation or scaling)
  101133. var targetPath = channel.target.path;
  101134. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  101135. if (targetPathIndex !== -1) {
  101136. targetPath = babylonAnimationPaths[targetPathIndex];
  101137. }
  101138. // Determine animation type
  101139. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  101140. if (!isBone) {
  101141. if (targetPath === "rotationQuaternion") {
  101142. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  101143. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  101144. }
  101145. else {
  101146. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  101147. }
  101148. }
  101149. // Create animation and key frames
  101150. var babylonAnimation = null;
  101151. var keys = [];
  101152. var arrayOffset = 0;
  101153. var modifyKey = false;
  101154. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  101155. babylonAnimation = lastAnimation;
  101156. modifyKey = true;
  101157. }
  101158. if (!modifyKey) {
  101159. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101160. }
  101161. // For each frame
  101162. for (var j = 0; j < bufferInput.length; j++) {
  101163. var value = null;
  101164. if (targetPath === "rotationQuaternion") {
  101165. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  101166. arrayOffset += 4;
  101167. }
  101168. else {
  101169. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  101170. arrayOffset += 3;
  101171. }
  101172. if (isBone) {
  101173. var bone = targetNode;
  101174. var translation = BABYLON.Vector3.Zero();
  101175. var rotationQuaternion = new BABYLON.Quaternion();
  101176. var scaling = BABYLON.Vector3.Zero();
  101177. // Warning on decompose
  101178. var mat = bone.getBaseMatrix();
  101179. if (modifyKey && lastAnimation) {
  101180. mat = lastAnimation.getKeys()[j].value;
  101181. }
  101182. mat.decompose(scaling, rotationQuaternion, translation);
  101183. if (targetPath === "position") {
  101184. translation = value;
  101185. }
  101186. else if (targetPath === "rotationQuaternion") {
  101187. rotationQuaternion = value;
  101188. }
  101189. else {
  101190. scaling = value;
  101191. }
  101192. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  101193. }
  101194. if (!modifyKey) {
  101195. keys.push({
  101196. frame: bufferInput[j],
  101197. value: value
  101198. });
  101199. }
  101200. else if (lastAnimation) {
  101201. lastAnimation.getKeys()[j].value = value;
  101202. }
  101203. }
  101204. // Finish
  101205. if (!modifyKey && babylonAnimation) {
  101206. babylonAnimation.setKeys(keys);
  101207. targetNode.animations.push(babylonAnimation);
  101208. }
  101209. lastAnimation = babylonAnimation;
  101210. gltfRuntime.scene.stopAnimation(targetNode);
  101211. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  101212. }
  101213. }
  101214. };
  101215. /**
  101216. * Returns the bones transformation matrix
  101217. */
  101218. var configureBoneTransformation = function (node) {
  101219. var mat = null;
  101220. if (node.translation || node.rotation || node.scale) {
  101221. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  101222. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  101223. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  101224. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  101225. }
  101226. else {
  101227. mat = BABYLON.Matrix.FromArray(node.matrix);
  101228. }
  101229. return mat;
  101230. };
  101231. /**
  101232. * Returns the parent bone
  101233. */
  101234. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  101235. // Try to find
  101236. for (var i = 0; i < newSkeleton.bones.length; i++) {
  101237. if (newSkeleton.bones[i].name === jointName) {
  101238. return newSkeleton.bones[i];
  101239. }
  101240. }
  101241. // Not found, search in gltf nodes
  101242. var nodes = gltfRuntime.nodes;
  101243. for (var nde in nodes) {
  101244. var node = nodes[nde];
  101245. if (!node.jointName) {
  101246. continue;
  101247. }
  101248. var children = node.children;
  101249. for (var i = 0; i < children.length; i++) {
  101250. var child = gltfRuntime.nodes[children[i]];
  101251. if (!child.jointName) {
  101252. continue;
  101253. }
  101254. if (child.jointName === jointName) {
  101255. var mat = configureBoneTransformation(node);
  101256. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  101257. bone.id = nde;
  101258. return bone;
  101259. }
  101260. }
  101261. }
  101262. return null;
  101263. };
  101264. /**
  101265. * Returns the appropriate root node
  101266. */
  101267. var getNodeToRoot = function (nodesToRoot, id) {
  101268. for (var i = 0; i < nodesToRoot.length; i++) {
  101269. var nodeToRoot = nodesToRoot[i];
  101270. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  101271. var child = nodeToRoot.node.children[j];
  101272. if (child === id) {
  101273. return nodeToRoot.bone;
  101274. }
  101275. }
  101276. }
  101277. return null;
  101278. };
  101279. /**
  101280. * Returns the node with the joint name
  101281. */
  101282. var getJointNode = function (gltfRuntime, jointName) {
  101283. var nodes = gltfRuntime.nodes;
  101284. var node = nodes[jointName];
  101285. if (node) {
  101286. return {
  101287. node: node,
  101288. id: jointName
  101289. };
  101290. }
  101291. for (var nde in nodes) {
  101292. node = nodes[nde];
  101293. if (node.jointName === jointName) {
  101294. return {
  101295. node: node,
  101296. id: nde
  101297. };
  101298. }
  101299. }
  101300. return null;
  101301. };
  101302. /**
  101303. * Checks if a nodes is in joints
  101304. */
  101305. var nodeIsInJoints = function (skins, id) {
  101306. for (var i = 0; i < skins.jointNames.length; i++) {
  101307. if (skins.jointNames[i] === id) {
  101308. return true;
  101309. }
  101310. }
  101311. return false;
  101312. };
  101313. /**
  101314. * Fills the nodes to root for bones and builds hierarchy
  101315. */
  101316. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  101317. // Creates nodes for root
  101318. for (var nde in gltfRuntime.nodes) {
  101319. var node = gltfRuntime.nodes[nde];
  101320. var id = nde;
  101321. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  101322. continue;
  101323. }
  101324. // Create node to root bone
  101325. var mat = configureBoneTransformation(node);
  101326. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  101327. bone.id = id;
  101328. nodesToRoot.push({ bone: bone, node: node, id: id });
  101329. }
  101330. // Parenting
  101331. for (var i = 0; i < nodesToRoot.length; i++) {
  101332. var nodeToRoot = nodesToRoot[i];
  101333. var children = nodeToRoot.node.children;
  101334. for (var j = 0; j < children.length; j++) {
  101335. var child = null;
  101336. for (var k = 0; k < nodesToRoot.length; k++) {
  101337. if (nodesToRoot[k].id === children[j]) {
  101338. child = nodesToRoot[k];
  101339. break;
  101340. }
  101341. }
  101342. if (child) {
  101343. child.bone._parent = nodeToRoot.bone;
  101344. nodeToRoot.bone.children.push(child.bone);
  101345. }
  101346. }
  101347. }
  101348. };
  101349. /**
  101350. * Imports a skeleton
  101351. */
  101352. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  101353. if (!newSkeleton) {
  101354. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  101355. }
  101356. if (!skins.babylonSkeleton) {
  101357. return newSkeleton;
  101358. }
  101359. // Find the root bones
  101360. var nodesToRoot = [];
  101361. var nodesToRootToAdd = [];
  101362. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  101363. newSkeleton.bones = [];
  101364. // Joints
  101365. for (var i = 0; i < skins.jointNames.length; i++) {
  101366. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  101367. if (!jointNode) {
  101368. continue;
  101369. }
  101370. var node = jointNode.node;
  101371. if (!node) {
  101372. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  101373. continue;
  101374. }
  101375. var id = jointNode.id;
  101376. // Optimize, if the bone already exists...
  101377. var existingBone = gltfRuntime.scene.getBoneByID(id);
  101378. if (existingBone) {
  101379. newSkeleton.bones.push(existingBone);
  101380. continue;
  101381. }
  101382. // Search for parent bone
  101383. var foundBone = false;
  101384. var parentBone = null;
  101385. for (var j = 0; j < i; j++) {
  101386. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  101387. if (!jointNode_1) {
  101388. continue;
  101389. }
  101390. var joint = jointNode_1.node;
  101391. if (!joint) {
  101392. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  101393. continue;
  101394. }
  101395. var children = joint.children;
  101396. if (!children) {
  101397. continue;
  101398. }
  101399. foundBone = false;
  101400. for (var k = 0; k < children.length; k++) {
  101401. if (children[k] === id) {
  101402. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  101403. foundBone = true;
  101404. break;
  101405. }
  101406. }
  101407. if (foundBone) {
  101408. break;
  101409. }
  101410. }
  101411. // Create bone
  101412. var mat = configureBoneTransformation(node);
  101413. if (!parentBone && nodesToRoot.length > 0) {
  101414. parentBone = getNodeToRoot(nodesToRoot, id);
  101415. if (parentBone) {
  101416. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  101417. nodesToRootToAdd.push(parentBone);
  101418. }
  101419. }
  101420. }
  101421. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  101422. bone.id = id;
  101423. }
  101424. // Polish
  101425. var bones = newSkeleton.bones;
  101426. newSkeleton.bones = [];
  101427. for (var i = 0; i < skins.jointNames.length; i++) {
  101428. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  101429. if (!jointNode) {
  101430. continue;
  101431. }
  101432. for (var j = 0; j < bones.length; j++) {
  101433. if (bones[j].id === jointNode.id) {
  101434. newSkeleton.bones.push(bones[j]);
  101435. break;
  101436. }
  101437. }
  101438. }
  101439. newSkeleton.prepare();
  101440. // Finish
  101441. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  101442. newSkeleton.bones.push(nodesToRootToAdd[i]);
  101443. }
  101444. return newSkeleton;
  101445. };
  101446. /**
  101447. * Imports a mesh and its geometries
  101448. */
  101449. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  101450. if (!newMesh) {
  101451. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  101452. newMesh.id = id;
  101453. }
  101454. if (!node.babylonNode) {
  101455. return newMesh;
  101456. }
  101457. var subMaterials = [];
  101458. var vertexData = null;
  101459. var verticesStarts = new Array();
  101460. var verticesCounts = new Array();
  101461. var indexStarts = new Array();
  101462. var indexCounts = new Array();
  101463. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  101464. var meshID = meshes[meshIndex];
  101465. var mesh = gltfRuntime.meshes[meshID];
  101466. if (!mesh) {
  101467. continue;
  101468. }
  101469. // Positions, normals and UVs
  101470. for (var i = 0; i < mesh.primitives.length; i++) {
  101471. // Temporary vertex data
  101472. var tempVertexData = new BABYLON.VertexData();
  101473. var primitive = mesh.primitives[i];
  101474. if (primitive.mode !== 4) {
  101475. // continue;
  101476. }
  101477. var attributes = primitive.attributes;
  101478. var accessor = null;
  101479. var buffer = null;
  101480. // Set positions, normal and uvs
  101481. for (var semantic in attributes) {
  101482. // Link accessor and buffer view
  101483. accessor = gltfRuntime.accessors[attributes[semantic]];
  101484. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  101485. if (semantic === "NORMAL") {
  101486. tempVertexData.normals = new Float32Array(buffer.length);
  101487. tempVertexData.normals.set(buffer);
  101488. }
  101489. else if (semantic === "POSITION") {
  101490. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  101491. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  101492. for (var j = 0; j < buffer.length; j += 4) {
  101493. tempVertexData.positions[j] = buffer[j];
  101494. tempVertexData.positions[j + 1] = buffer[j + 1];
  101495. tempVertexData.positions[j + 2] = buffer[j + 2];
  101496. }
  101497. }
  101498. else {
  101499. tempVertexData.positions = new Float32Array(buffer.length);
  101500. tempVertexData.positions.set(buffer);
  101501. }
  101502. verticesCounts.push(tempVertexData.positions.length);
  101503. }
  101504. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  101505. var channel = Number(semantic.split("_")[1]);
  101506. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  101507. var uvs = new Float32Array(buffer.length);
  101508. uvs.set(buffer);
  101509. normalizeUVs(uvs);
  101510. tempVertexData.set(uvs, uvKind);
  101511. }
  101512. else if (semantic === "JOINT") {
  101513. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  101514. tempVertexData.matricesIndices.set(buffer);
  101515. }
  101516. else if (semantic === "WEIGHT") {
  101517. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  101518. tempVertexData.matricesWeights.set(buffer);
  101519. }
  101520. else if (semantic === "COLOR") {
  101521. tempVertexData.colors = new Float32Array(buffer.length);
  101522. tempVertexData.colors.set(buffer);
  101523. }
  101524. }
  101525. // Indices
  101526. accessor = gltfRuntime.accessors[primitive.indices];
  101527. if (accessor) {
  101528. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  101529. tempVertexData.indices = new Int32Array(buffer.length);
  101530. tempVertexData.indices.set(buffer);
  101531. indexCounts.push(tempVertexData.indices.length);
  101532. }
  101533. else {
  101534. // Set indices on the fly
  101535. var indices = [];
  101536. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  101537. indices.push(j);
  101538. }
  101539. tempVertexData.indices = new Int32Array(indices);
  101540. indexCounts.push(tempVertexData.indices.length);
  101541. }
  101542. if (!vertexData) {
  101543. vertexData = tempVertexData;
  101544. }
  101545. else {
  101546. vertexData.merge(tempVertexData);
  101547. }
  101548. // Sub material
  101549. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  101550. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  101551. // Update vertices start and index start
  101552. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  101553. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  101554. }
  101555. }
  101556. var material;
  101557. if (subMaterials.length > 1) {
  101558. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  101559. material.subMaterials = subMaterials;
  101560. }
  101561. else {
  101562. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  101563. }
  101564. if (subMaterials.length === 1) {
  101565. material = subMaterials[0];
  101566. }
  101567. if (!newMesh.material) {
  101568. newMesh.material = material;
  101569. }
  101570. // Apply geometry
  101571. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  101572. newMesh.computeWorldMatrix(true);
  101573. // Apply submeshes
  101574. newMesh.subMeshes = [];
  101575. var index = 0;
  101576. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  101577. var meshID = meshes[meshIndex];
  101578. var mesh = gltfRuntime.meshes[meshID];
  101579. if (!mesh) {
  101580. continue;
  101581. }
  101582. for (var i = 0; i < mesh.primitives.length; i++) {
  101583. if (mesh.primitives[i].mode !== 4) {
  101584. //continue;
  101585. }
  101586. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  101587. index++;
  101588. }
  101589. }
  101590. // Finish
  101591. return newMesh;
  101592. };
  101593. /**
  101594. * Configure node transformation from position, rotation and scaling
  101595. */
  101596. var configureNode = function (newNode, position, rotation, scaling) {
  101597. if (newNode.position) {
  101598. newNode.position = position;
  101599. }
  101600. if (newNode.rotationQuaternion || newNode.rotation) {
  101601. newNode.rotationQuaternion = rotation;
  101602. }
  101603. if (newNode.scaling) {
  101604. newNode.scaling = scaling;
  101605. }
  101606. };
  101607. /**
  101608. * Configures node from transformation matrix
  101609. */
  101610. var configureNodeFromMatrix = function (newNode, node, parent) {
  101611. if (node.matrix) {
  101612. var position = new BABYLON.Vector3(0, 0, 0);
  101613. var rotation = new BABYLON.Quaternion();
  101614. var scaling = new BABYLON.Vector3(0, 0, 0);
  101615. var mat = BABYLON.Matrix.FromArray(node.matrix);
  101616. mat.decompose(scaling, rotation, position);
  101617. configureNode(newNode, position, rotation, scaling);
  101618. }
  101619. else if (node.translation && node.rotation && node.scale) {
  101620. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  101621. }
  101622. newNode.computeWorldMatrix(true);
  101623. };
  101624. /**
  101625. * Imports a node
  101626. */
  101627. var importNode = function (gltfRuntime, node, id, parent) {
  101628. var lastNode = null;
  101629. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  101630. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  101631. return null;
  101632. }
  101633. }
  101634. // Meshes
  101635. if (node.skin) {
  101636. if (node.meshes) {
  101637. var skin = gltfRuntime.skins[node.skin];
  101638. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  101639. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  101640. if (newMesh.skeleton === null) {
  101641. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  101642. if (!skin.babylonSkeleton) {
  101643. skin.babylonSkeleton = newMesh.skeleton;
  101644. }
  101645. }
  101646. lastNode = newMesh;
  101647. }
  101648. }
  101649. else if (node.meshes) {
  101650. /**
  101651. * Improve meshes property
  101652. */
  101653. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  101654. lastNode = newMesh;
  101655. }
  101656. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  101657. var light = gltfRuntime.lights[node.light];
  101658. if (light) {
  101659. if (light.type === "ambient") {
  101660. var ambienLight = light[light.type];
  101661. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101662. hemiLight.name = node.name || "";
  101663. if (ambienLight.color) {
  101664. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  101665. }
  101666. lastNode = hemiLight;
  101667. }
  101668. else if (light.type === "directional") {
  101669. var directionalLight = light[light.type];
  101670. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101671. dirLight.name = node.name || "";
  101672. if (directionalLight.color) {
  101673. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  101674. }
  101675. lastNode = dirLight;
  101676. }
  101677. else if (light.type === "point") {
  101678. var pointLight = light[light.type];
  101679. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101680. ptLight.name = node.name || "";
  101681. if (pointLight.color) {
  101682. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  101683. }
  101684. lastNode = ptLight;
  101685. }
  101686. else if (light.type === "spot") {
  101687. var spotLight = light[light.type];
  101688. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  101689. spLight.name = node.name || "";
  101690. if (spotLight.color) {
  101691. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  101692. }
  101693. if (spotLight.fallOfAngle) {
  101694. spLight.angle = spotLight.fallOfAngle;
  101695. }
  101696. if (spotLight.fallOffExponent) {
  101697. spLight.exponent = spotLight.fallOffExponent;
  101698. }
  101699. lastNode = spLight;
  101700. }
  101701. }
  101702. }
  101703. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  101704. var camera = gltfRuntime.cameras[node.camera];
  101705. if (camera) {
  101706. if (camera.type === "orthographic") {
  101707. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101708. orthoCamera.name = node.name || "";
  101709. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  101710. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  101711. lastNode = orthoCamera;
  101712. }
  101713. else if (camera.type === "perspective") {
  101714. var perspectiveCamera = camera[camera.type];
  101715. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101716. persCamera.name = node.name || "";
  101717. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  101718. if (!perspectiveCamera.aspectRatio) {
  101719. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  101720. }
  101721. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  101722. persCamera.maxZ = perspectiveCamera.zfar;
  101723. persCamera.minZ = perspectiveCamera.znear;
  101724. }
  101725. lastNode = persCamera;
  101726. }
  101727. }
  101728. }
  101729. // Empty node
  101730. if (!node.jointName) {
  101731. if (node.babylonNode) {
  101732. return node.babylonNode;
  101733. }
  101734. else if (lastNode === null) {
  101735. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  101736. node.babylonNode = dummy;
  101737. lastNode = dummy;
  101738. }
  101739. }
  101740. if (lastNode !== null) {
  101741. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  101742. configureNodeFromMatrix(lastNode, node, parent);
  101743. }
  101744. else {
  101745. var translation = node.translation || [0, 0, 0];
  101746. var rotation = node.rotation || [0, 0, 0, 1];
  101747. var scale = node.scale || [1, 1, 1];
  101748. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  101749. }
  101750. lastNode.updateCache(true);
  101751. node.babylonNode = lastNode;
  101752. }
  101753. return lastNode;
  101754. };
  101755. /**
  101756. * Traverses nodes and creates them
  101757. */
  101758. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  101759. if (meshIncluded === void 0) { meshIncluded = false; }
  101760. var node = gltfRuntime.nodes[id];
  101761. var newNode = null;
  101762. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  101763. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  101764. meshIncluded = true;
  101765. }
  101766. else {
  101767. meshIncluded = false;
  101768. }
  101769. }
  101770. else {
  101771. meshIncluded = true;
  101772. }
  101773. if (!node.jointName && meshIncluded) {
  101774. newNode = importNode(gltfRuntime, node, id, parent);
  101775. if (newNode !== null) {
  101776. newNode.id = id;
  101777. newNode.parent = parent;
  101778. }
  101779. }
  101780. if (node.children) {
  101781. for (var i = 0; i < node.children.length; i++) {
  101782. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  101783. }
  101784. }
  101785. };
  101786. /**
  101787. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  101788. */
  101789. var postLoad = function (gltfRuntime) {
  101790. // Nodes
  101791. var currentScene = gltfRuntime.currentScene;
  101792. if (currentScene) {
  101793. for (var i = 0; i < currentScene.nodes.length; i++) {
  101794. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  101795. }
  101796. }
  101797. else {
  101798. for (var thing in gltfRuntime.scenes) {
  101799. currentScene = gltfRuntime.scenes[thing];
  101800. for (var i = 0; i < currentScene.nodes.length; i++) {
  101801. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  101802. }
  101803. }
  101804. }
  101805. // Set animations
  101806. loadAnimations(gltfRuntime);
  101807. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  101808. var skeleton = gltfRuntime.scene.skeletons[i];
  101809. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  101810. }
  101811. };
  101812. /**
  101813. * onBind shaderrs callback to set uniforms and matrices
  101814. */
  101815. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  101816. var materialValues = material.values || technique.parameters;
  101817. for (var unif in unTreatedUniforms) {
  101818. var uniform = unTreatedUniforms[unif];
  101819. var type = uniform.type;
  101820. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  101821. if (uniform.semantic && !uniform.source && !uniform.node) {
  101822. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  101823. }
  101824. else if (uniform.semantic && (uniform.source || uniform.node)) {
  101825. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  101826. if (source === null) {
  101827. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  101828. }
  101829. if (source === null) {
  101830. continue;
  101831. }
  101832. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  101833. }
  101834. }
  101835. else {
  101836. var value = materialValues[technique.uniforms[unif]];
  101837. if (!value) {
  101838. continue;
  101839. }
  101840. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  101841. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  101842. if (texture === null || texture === undefined) {
  101843. continue;
  101844. }
  101845. shaderMaterial.getEffect().setTexture(unif, texture);
  101846. }
  101847. else {
  101848. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  101849. }
  101850. }
  101851. }
  101852. onSuccess(shaderMaterial);
  101853. };
  101854. /**
  101855. * Prepare uniforms to send the only one time
  101856. * Loads the appropriate textures
  101857. */
  101858. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  101859. var materialValues = material.values || technique.parameters;
  101860. var techniqueUniforms = technique.uniforms;
  101861. /**
  101862. * Prepare values here (not matrices)
  101863. */
  101864. for (var unif in unTreatedUniforms) {
  101865. var uniform = unTreatedUniforms[unif];
  101866. var type = uniform.type;
  101867. var value = materialValues[techniqueUniforms[unif]];
  101868. if (value === undefined) {
  101869. // In case the value is the same for all materials
  101870. value = uniform.value;
  101871. }
  101872. if (!value) {
  101873. continue;
  101874. }
  101875. var onLoadTexture = function (uniformName) {
  101876. return function (texture) {
  101877. if (uniform.value && uniformName) {
  101878. // Static uniform
  101879. shaderMaterial.setTexture(uniformName, texture);
  101880. delete unTreatedUniforms[uniformName];
  101881. }
  101882. };
  101883. };
  101884. // Texture (sampler2D)
  101885. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  101886. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  101887. }
  101888. else {
  101889. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  101890. // Static uniform
  101891. delete unTreatedUniforms[unif];
  101892. }
  101893. }
  101894. }
  101895. };
  101896. /**
  101897. * Shader compilation failed
  101898. */
  101899. var onShaderCompileError = function (program, shaderMaterial, onError) {
  101900. return function (effect, error) {
  101901. shaderMaterial.dispose(true);
  101902. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  101903. };
  101904. };
  101905. /**
  101906. * Shader compilation success
  101907. */
  101908. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  101909. return function (_) {
  101910. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  101911. shaderMaterial.onBind = function (mesh) {
  101912. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  101913. };
  101914. };
  101915. };
  101916. /**
  101917. * Returns the appropriate uniform if already handled by babylon
  101918. */
  101919. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  101920. for (var unif in technique.uniforms) {
  101921. var uniform = technique.uniforms[unif];
  101922. var uniformParameter = technique.parameters[uniform];
  101923. if (tokenizer.currentIdentifier === unif) {
  101924. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  101925. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  101926. if (transformIndex !== -1) {
  101927. delete unTreatedUniforms[unif];
  101928. return babylonTransforms[transformIndex];
  101929. }
  101930. }
  101931. }
  101932. }
  101933. return tokenizer.currentIdentifier;
  101934. };
  101935. /**
  101936. * All shaders loaded. Create materials one by one
  101937. */
  101938. var importMaterials = function (gltfRuntime) {
  101939. // Create materials
  101940. for (var mat in gltfRuntime.materials) {
  101941. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  101942. }
  101943. };
  101944. /**
  101945. * Implementation of the base glTF spec
  101946. */
  101947. var GLTFLoaderBase = /** @class */ (function () {
  101948. function GLTFLoaderBase() {
  101949. }
  101950. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  101951. var gltfRuntime = {
  101952. extensions: {},
  101953. accessors: {},
  101954. buffers: {},
  101955. bufferViews: {},
  101956. meshes: {},
  101957. lights: {},
  101958. cameras: {},
  101959. nodes: {},
  101960. images: {},
  101961. textures: {},
  101962. shaders: {},
  101963. programs: {},
  101964. samplers: {},
  101965. techniques: {},
  101966. materials: {},
  101967. animations: {},
  101968. skins: {},
  101969. extensionsUsed: [],
  101970. scenes: {},
  101971. buffersCount: 0,
  101972. shaderscount: 0,
  101973. scene: scene,
  101974. rootUrl: rootUrl,
  101975. loadedBufferCount: 0,
  101976. loadedBufferViews: {},
  101977. loadedShaderCount: 0,
  101978. importOnlyMeshes: false,
  101979. dummyNodes: []
  101980. };
  101981. // Parse
  101982. if (parsedData.extensions) {
  101983. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  101984. }
  101985. if (parsedData.extensionsUsed) {
  101986. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  101987. }
  101988. if (parsedData.buffers) {
  101989. parseBuffers(parsedData.buffers, gltfRuntime);
  101990. }
  101991. if (parsedData.bufferViews) {
  101992. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  101993. }
  101994. if (parsedData.accessors) {
  101995. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  101996. }
  101997. if (parsedData.meshes) {
  101998. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  101999. }
  102000. if (parsedData.lights) {
  102001. parseObject(parsedData.lights, "lights", gltfRuntime);
  102002. }
  102003. if (parsedData.cameras) {
  102004. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  102005. }
  102006. if (parsedData.nodes) {
  102007. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  102008. }
  102009. if (parsedData.images) {
  102010. parseObject(parsedData.images, "images", gltfRuntime);
  102011. }
  102012. if (parsedData.textures) {
  102013. parseObject(parsedData.textures, "textures", gltfRuntime);
  102014. }
  102015. if (parsedData.shaders) {
  102016. parseShaders(parsedData.shaders, gltfRuntime);
  102017. }
  102018. if (parsedData.programs) {
  102019. parseObject(parsedData.programs, "programs", gltfRuntime);
  102020. }
  102021. if (parsedData.samplers) {
  102022. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  102023. }
  102024. if (parsedData.techniques) {
  102025. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  102026. }
  102027. if (parsedData.materials) {
  102028. parseObject(parsedData.materials, "materials", gltfRuntime);
  102029. }
  102030. if (parsedData.animations) {
  102031. parseObject(parsedData.animations, "animations", gltfRuntime);
  102032. }
  102033. if (parsedData.skins) {
  102034. parseObject(parsedData.skins, "skins", gltfRuntime);
  102035. }
  102036. if (parsedData.scenes) {
  102037. gltfRuntime.scenes = parsedData.scenes;
  102038. }
  102039. if (parsedData.scene && parsedData.scenes) {
  102040. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  102041. }
  102042. return gltfRuntime;
  102043. };
  102044. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102045. var buffer = gltfRuntime.buffers[id];
  102046. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  102047. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  102048. }
  102049. else {
  102050. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  102051. if (request) {
  102052. onError(request.status + " " + request.statusText);
  102053. }
  102054. });
  102055. }
  102056. };
  102057. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102058. var texture = gltfRuntime.textures[id];
  102059. if (!texture || !texture.source) {
  102060. onError("");
  102061. return;
  102062. }
  102063. if (texture.babylonTexture) {
  102064. onSuccess(null);
  102065. return;
  102066. }
  102067. var source = gltfRuntime.images[texture.source];
  102068. if (BABYLON.Tools.IsBase64(source.uri)) {
  102069. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  102070. }
  102071. else {
  102072. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  102073. if (request) {
  102074. onError(request.status + " " + request.statusText);
  102075. }
  102076. });
  102077. }
  102078. };
  102079. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102080. var texture = gltfRuntime.textures[id];
  102081. if (texture.babylonTexture) {
  102082. onSuccess(texture.babylonTexture);
  102083. return;
  102084. }
  102085. var sampler = gltfRuntime.samplers[texture.sampler];
  102086. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  102087. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  102088. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  102089. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  102090. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  102091. var blob = new Blob([buffer]);
  102092. var blobURL = URL.createObjectURL(blob);
  102093. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  102094. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  102095. if (sampler.wrapS !== undefined) {
  102096. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  102097. }
  102098. if (sampler.wrapT !== undefined) {
  102099. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  102100. }
  102101. newTexture.name = id;
  102102. texture.babylonTexture = newTexture;
  102103. onSuccess(newTexture);
  102104. };
  102105. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102106. var shader = gltfRuntime.shaders[id];
  102107. if (BABYLON.Tools.IsBase64(shader.uri)) {
  102108. var shaderString = atob(shader.uri.split(",")[1]);
  102109. if (onSuccess) {
  102110. onSuccess(shaderString);
  102111. }
  102112. }
  102113. else {
  102114. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  102115. if (request && onError) {
  102116. onError(request.status + " " + request.statusText);
  102117. }
  102118. });
  102119. }
  102120. };
  102121. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102122. var material = gltfRuntime.materials[id];
  102123. if (!material.technique) {
  102124. if (onError) {
  102125. onError("No technique found.");
  102126. }
  102127. return;
  102128. }
  102129. var technique = gltfRuntime.techniques[material.technique];
  102130. if (!technique) {
  102131. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  102132. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  102133. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102134. onSuccess(defaultMaterial);
  102135. return;
  102136. }
  102137. var program = gltfRuntime.programs[technique.program];
  102138. var states = technique.states;
  102139. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  102140. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  102141. var newVertexShader = "";
  102142. var newPixelShader = "";
  102143. var vertexTokenizer = new Tokenizer(vertexShader);
  102144. var pixelTokenizer = new Tokenizer(pixelShader);
  102145. var unTreatedUniforms = {};
  102146. var uniforms = [];
  102147. var attributes = [];
  102148. var samplers = [];
  102149. // Fill uniform, sampler2D and attributes
  102150. for (var unif in technique.uniforms) {
  102151. var uniform = technique.uniforms[unif];
  102152. var uniformParameter = technique.parameters[uniform];
  102153. unTreatedUniforms[unif] = uniformParameter;
  102154. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  102155. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102156. if (transformIndex !== -1) {
  102157. uniforms.push(babylonTransforms[transformIndex]);
  102158. delete unTreatedUniforms[unif];
  102159. }
  102160. else {
  102161. uniforms.push(unif);
  102162. }
  102163. }
  102164. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  102165. samplers.push(unif);
  102166. }
  102167. else {
  102168. uniforms.push(unif);
  102169. }
  102170. }
  102171. for (var attr in technique.attributes) {
  102172. var attribute = technique.attributes[attr];
  102173. var attributeParameter = technique.parameters[attribute];
  102174. if (attributeParameter.semantic) {
  102175. attributes.push(getAttribute(attributeParameter));
  102176. }
  102177. }
  102178. // Configure vertex shader
  102179. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  102180. var tokenType = vertexTokenizer.currentToken;
  102181. if (tokenType !== ETokenType.IDENTIFIER) {
  102182. newVertexShader += vertexTokenizer.currentString;
  102183. continue;
  102184. }
  102185. var foundAttribute = false;
  102186. for (var attr in technique.attributes) {
  102187. var attribute = technique.attributes[attr];
  102188. var attributeParameter = technique.parameters[attribute];
  102189. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  102190. newVertexShader += getAttribute(attributeParameter);
  102191. foundAttribute = true;
  102192. break;
  102193. }
  102194. }
  102195. if (foundAttribute) {
  102196. continue;
  102197. }
  102198. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  102199. }
  102200. // Configure pixel shader
  102201. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  102202. var tokenType = pixelTokenizer.currentToken;
  102203. if (tokenType !== ETokenType.IDENTIFIER) {
  102204. newPixelShader += pixelTokenizer.currentString;
  102205. continue;
  102206. }
  102207. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  102208. }
  102209. // Create shader material
  102210. var shaderPath = {
  102211. vertex: program.vertexShader + id,
  102212. fragment: program.fragmentShader + id
  102213. };
  102214. var options = {
  102215. attributes: attributes,
  102216. uniforms: uniforms,
  102217. samplers: samplers,
  102218. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  102219. };
  102220. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  102221. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  102222. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  102223. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  102224. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  102225. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102226. if (states && states.functions) {
  102227. var functions = states.functions;
  102228. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  102229. shaderMaterial.backFaceCulling = false;
  102230. }
  102231. var blendFunc = functions.blendFuncSeparate;
  102232. if (blendFunc) {
  102233. 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) {
  102234. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  102235. }
  102236. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102237. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  102238. }
  102239. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102240. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  102241. }
  102242. 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) {
  102243. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  102244. }
  102245. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102246. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  102247. }
  102248. 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) {
  102249. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  102250. }
  102251. }
  102252. }
  102253. };
  102254. return GLTFLoaderBase;
  102255. }());
  102256. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  102257. /**
  102258. * glTF V1 Loader
  102259. */
  102260. var GLTFLoader = /** @class */ (function () {
  102261. function GLTFLoader() {
  102262. // #region Stubs for IGLTFLoader interface
  102263. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  102264. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  102265. this.compileMaterials = false;
  102266. this.useClipPlane = false;
  102267. this.compileShadowGenerators = false;
  102268. this.onDisposeObservable = new BABYLON.Observable();
  102269. this.onMeshLoadedObservable = new BABYLON.Observable();
  102270. this.onTextureLoadedObservable = new BABYLON.Observable();
  102271. this.onMaterialLoadedObservable = new BABYLON.Observable();
  102272. this.onCompleteObservable = new BABYLON.Observable();
  102273. this.onExtensionLoadedObservable = new BABYLON.Observable();
  102274. this.state = null;
  102275. }
  102276. GLTFLoader.RegisterExtension = function (extension) {
  102277. if (GLTFLoader.Extensions[extension.name]) {
  102278. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  102279. return;
  102280. }
  102281. GLTFLoader.Extensions[extension.name] = extension;
  102282. };
  102283. GLTFLoader.prototype.dispose = function () { };
  102284. // #endregion
  102285. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  102286. var _this = this;
  102287. scene.useRightHandedSystem = true;
  102288. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102289. gltfRuntime.importOnlyMeshes = true;
  102290. if (meshesNames === "") {
  102291. gltfRuntime.importMeshesNames = [];
  102292. }
  102293. else if (typeof meshesNames === "string") {
  102294. gltfRuntime.importMeshesNames = [meshesNames];
  102295. }
  102296. else if (meshesNames && !(meshesNames instanceof Array)) {
  102297. gltfRuntime.importMeshesNames = [meshesNames];
  102298. }
  102299. else {
  102300. gltfRuntime.importMeshesNames = [];
  102301. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  102302. }
  102303. // Create nodes
  102304. _this._createNodes(gltfRuntime);
  102305. var meshes = new Array();
  102306. var skeletons = new Array();
  102307. // Fill arrays of meshes and skeletons
  102308. for (var nde in gltfRuntime.nodes) {
  102309. var node = gltfRuntime.nodes[nde];
  102310. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  102311. meshes.push(node.babylonNode);
  102312. }
  102313. }
  102314. for (var skl in gltfRuntime.skins) {
  102315. var skin = gltfRuntime.skins[skl];
  102316. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  102317. skeletons.push(skin.babylonSkeleton);
  102318. }
  102319. }
  102320. // Load buffers, shaders, materials, etc.
  102321. _this._loadBuffersAsync(gltfRuntime, function () {
  102322. _this._loadShadersAsync(gltfRuntime, function () {
  102323. importMaterials(gltfRuntime);
  102324. postLoad(gltfRuntime);
  102325. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102326. onSuccess(meshes, skeletons);
  102327. }
  102328. });
  102329. }, onProgress);
  102330. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102331. onSuccess(meshes, skeletons);
  102332. }
  102333. }, onError);
  102334. return true;
  102335. };
  102336. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102337. var _this = this;
  102338. return new Promise(function (resolve, reject) {
  102339. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  102340. resolve({
  102341. meshes: meshes,
  102342. particleSystems: [],
  102343. skeletons: skeletons,
  102344. animationGroups: []
  102345. });
  102346. }, onProgress, function (message) {
  102347. reject(new Error(message));
  102348. });
  102349. });
  102350. };
  102351. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  102352. var _this = this;
  102353. scene.useRightHandedSystem = true;
  102354. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102355. // Load runtime extensios
  102356. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  102357. // Create nodes
  102358. _this._createNodes(gltfRuntime);
  102359. // Load buffers, shaders, materials, etc.
  102360. _this._loadBuffersAsync(gltfRuntime, function () {
  102361. _this._loadShadersAsync(gltfRuntime, function () {
  102362. importMaterials(gltfRuntime);
  102363. postLoad(gltfRuntime);
  102364. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  102365. onSuccess();
  102366. }
  102367. });
  102368. });
  102369. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  102370. onSuccess();
  102371. }
  102372. }, onError);
  102373. }, onError);
  102374. };
  102375. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  102376. var _this = this;
  102377. return new Promise(function (resolve, reject) {
  102378. _this._loadAsync(scene, data, rootUrl, function () {
  102379. resolve();
  102380. }, onProgress, function (message) {
  102381. reject(new Error(message));
  102382. });
  102383. });
  102384. };
  102385. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  102386. var hasShaders = false;
  102387. var processShader = function (sha, shader) {
  102388. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  102389. if (shaderString instanceof ArrayBuffer) {
  102390. return;
  102391. }
  102392. gltfRuntime.loadedShaderCount++;
  102393. if (shaderString) {
  102394. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  102395. }
  102396. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  102397. onload();
  102398. }
  102399. }, function () {
  102400. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  102401. });
  102402. };
  102403. for (var sha in gltfRuntime.shaders) {
  102404. hasShaders = true;
  102405. var shader = gltfRuntime.shaders[sha];
  102406. if (shader) {
  102407. processShader.bind(this, sha, shader)();
  102408. }
  102409. else {
  102410. BABYLON.Tools.Error("No shader named: " + sha);
  102411. }
  102412. }
  102413. if (!hasShaders) {
  102414. onload();
  102415. }
  102416. };
  102417. ;
  102418. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  102419. var hasBuffers = false;
  102420. var processBuffer = function (buf, buffer) {
  102421. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  102422. gltfRuntime.loadedBufferCount++;
  102423. if (bufferView) {
  102424. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  102425. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  102426. }
  102427. gltfRuntime.loadedBufferViews[buf] = bufferView;
  102428. }
  102429. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  102430. onLoad();
  102431. }
  102432. }, function () {
  102433. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  102434. });
  102435. };
  102436. for (var buf in gltfRuntime.buffers) {
  102437. hasBuffers = true;
  102438. var buffer = gltfRuntime.buffers[buf];
  102439. if (buffer) {
  102440. processBuffer.bind(this, buf, buffer)();
  102441. }
  102442. else {
  102443. BABYLON.Tools.Error("No buffer named: " + buf);
  102444. }
  102445. }
  102446. if (!hasBuffers) {
  102447. onLoad();
  102448. }
  102449. };
  102450. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  102451. var currentScene = gltfRuntime.currentScene;
  102452. if (currentScene) {
  102453. // Only one scene even if multiple scenes are defined
  102454. for (var i = 0; i < currentScene.nodes.length; i++) {
  102455. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102456. }
  102457. }
  102458. else {
  102459. // Load all scenes
  102460. for (var thing in gltfRuntime.scenes) {
  102461. currentScene = gltfRuntime.scenes[thing];
  102462. for (var i = 0; i < currentScene.nodes.length; i++) {
  102463. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102464. }
  102465. }
  102466. }
  102467. };
  102468. GLTFLoader.Extensions = {};
  102469. return GLTFLoader;
  102470. }());
  102471. GLTF1.GLTFLoader = GLTFLoader;
  102472. ;
  102473. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  102474. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102475. })(BABYLON || (BABYLON = {}));
  102476. //# sourceMappingURL=babylon.glTFLoader.js.map
  102477. "use strict";
  102478. var BABYLON;
  102479. (function (BABYLON) {
  102480. var GLTF1;
  102481. (function (GLTF1) {
  102482. /**
  102483. * Utils functions for GLTF
  102484. */
  102485. var GLTFUtils = /** @class */ (function () {
  102486. function GLTFUtils() {
  102487. }
  102488. /**
  102489. * Sets the given "parameter" matrix
  102490. * @param scene: the {BABYLON.Scene} object
  102491. * @param source: the source node where to pick the matrix
  102492. * @param parameter: the GLTF technique parameter
  102493. * @param uniformName: the name of the shader's uniform
  102494. * @param shaderMaterial: the shader material
  102495. */
  102496. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  102497. var mat = null;
  102498. if (parameter.semantic === "MODEL") {
  102499. mat = source.getWorldMatrix();
  102500. }
  102501. else if (parameter.semantic === "PROJECTION") {
  102502. mat = scene.getProjectionMatrix();
  102503. }
  102504. else if (parameter.semantic === "VIEW") {
  102505. mat = scene.getViewMatrix();
  102506. }
  102507. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  102508. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  102509. }
  102510. else if (parameter.semantic === "MODELVIEW") {
  102511. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  102512. }
  102513. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  102514. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  102515. }
  102516. else if (parameter.semantic === "MODELINVERSE") {
  102517. mat = source.getWorldMatrix().invert();
  102518. }
  102519. else if (parameter.semantic === "VIEWINVERSE") {
  102520. mat = scene.getViewMatrix().invert();
  102521. }
  102522. else if (parameter.semantic === "PROJECTIONINVERSE") {
  102523. mat = scene.getProjectionMatrix().invert();
  102524. }
  102525. else if (parameter.semantic === "MODELVIEWINVERSE") {
  102526. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  102527. }
  102528. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  102529. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  102530. }
  102531. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  102532. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  102533. }
  102534. else {
  102535. debugger;
  102536. }
  102537. if (mat) {
  102538. switch (parameter.type) {
  102539. case GLTF1.EParameterType.FLOAT_MAT2:
  102540. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  102541. break;
  102542. case GLTF1.EParameterType.FLOAT_MAT3:
  102543. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  102544. break;
  102545. case GLTF1.EParameterType.FLOAT_MAT4:
  102546. shaderMaterial.setMatrix(uniformName, mat);
  102547. break;
  102548. default: break;
  102549. }
  102550. }
  102551. };
  102552. /**
  102553. * Sets the given "parameter" matrix
  102554. * @param shaderMaterial: the shader material
  102555. * @param uniform: the name of the shader's uniform
  102556. * @param value: the value of the uniform
  102557. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  102558. */
  102559. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  102560. switch (type) {
  102561. case GLTF1.EParameterType.FLOAT:
  102562. shaderMaterial.setFloat(uniform, value);
  102563. return true;
  102564. case GLTF1.EParameterType.FLOAT_VEC2:
  102565. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  102566. return true;
  102567. case GLTF1.EParameterType.FLOAT_VEC3:
  102568. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  102569. return true;
  102570. case GLTF1.EParameterType.FLOAT_VEC4:
  102571. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  102572. return true;
  102573. default: return false;
  102574. }
  102575. };
  102576. /**
  102577. * Returns the wrap mode of the texture
  102578. * @param mode: the mode value
  102579. */
  102580. GLTFUtils.GetWrapMode = function (mode) {
  102581. switch (mode) {
  102582. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  102583. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  102584. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  102585. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  102586. }
  102587. };
  102588. /**
  102589. * Returns the byte stride giving an accessor
  102590. * @param accessor: the GLTF accessor objet
  102591. */
  102592. GLTFUtils.GetByteStrideFromType = function (accessor) {
  102593. // Needs this function since "byteStride" isn't requiered in glTF format
  102594. var type = accessor.type;
  102595. switch (type) {
  102596. case "VEC2": return 2;
  102597. case "VEC3": return 3;
  102598. case "VEC4": return 4;
  102599. case "MAT2": return 4;
  102600. case "MAT3": return 9;
  102601. case "MAT4": return 16;
  102602. default: return 1;
  102603. }
  102604. };
  102605. /**
  102606. * Returns the texture filter mode giving a mode value
  102607. * @param mode: the filter mode value
  102608. */
  102609. GLTFUtils.GetTextureFilterMode = function (mode) {
  102610. switch (mode) {
  102611. case GLTF1.ETextureFilterType.LINEAR:
  102612. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  102613. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  102614. case GLTF1.ETextureFilterType.NEAREST:
  102615. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  102616. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  102617. }
  102618. };
  102619. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  102620. var byteOffset = bufferView.byteOffset + byteOffset;
  102621. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  102622. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  102623. throw new Error("Buffer access is out of range");
  102624. }
  102625. var buffer = loadedBufferView.buffer;
  102626. byteOffset += loadedBufferView.byteOffset;
  102627. switch (componentType) {
  102628. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  102629. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  102630. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  102631. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  102632. default: return new Float32Array(buffer, byteOffset, byteLength);
  102633. }
  102634. };
  102635. /**
  102636. * Returns a buffer from its accessor
  102637. * @param gltfRuntime: the GLTF runtime
  102638. * @param accessor: the GLTF accessor
  102639. */
  102640. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  102641. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  102642. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  102643. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  102644. };
  102645. /**
  102646. * Decodes a buffer view into a string
  102647. * @param view: the buffer view
  102648. */
  102649. GLTFUtils.DecodeBufferToText = function (view) {
  102650. var result = "";
  102651. var length = view.byteLength;
  102652. for (var i = 0; i < length; ++i) {
  102653. result += String.fromCharCode(view[i]);
  102654. }
  102655. return result;
  102656. };
  102657. /**
  102658. * Returns the default material of gltf. Related to
  102659. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  102660. * @param scene: the Babylon.js scene
  102661. */
  102662. GLTFUtils.GetDefaultMaterial = function (scene) {
  102663. if (!GLTFUtils._DefaultMaterial) {
  102664. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  102665. "precision highp float;",
  102666. "",
  102667. "uniform mat4 worldView;",
  102668. "uniform mat4 projection;",
  102669. "",
  102670. "attribute vec3 position;",
  102671. "",
  102672. "void main(void)",
  102673. "{",
  102674. " gl_Position = projection * worldView * vec4(position, 1.0);",
  102675. "}"
  102676. ].join("\n");
  102677. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  102678. "precision highp float;",
  102679. "",
  102680. "uniform vec4 u_emission;",
  102681. "",
  102682. "void main(void)",
  102683. "{",
  102684. " gl_FragColor = u_emission;",
  102685. "}"
  102686. ].join("\n");
  102687. var shaderPath = {
  102688. vertex: "GLTFDefaultMaterial",
  102689. fragment: "GLTFDefaultMaterial"
  102690. };
  102691. var options = {
  102692. attributes: ["position"],
  102693. uniforms: ["worldView", "projection", "u_emission"],
  102694. samplers: new Array(),
  102695. needAlphaBlending: false
  102696. };
  102697. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  102698. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  102699. }
  102700. return GLTFUtils._DefaultMaterial;
  102701. };
  102702. // The GLTF default material
  102703. GLTFUtils._DefaultMaterial = null;
  102704. return GLTFUtils;
  102705. }());
  102706. GLTF1.GLTFUtils = GLTFUtils;
  102707. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102708. })(BABYLON || (BABYLON = {}));
  102709. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  102710. "use strict";
  102711. var BABYLON;
  102712. (function (BABYLON) {
  102713. var GLTF1;
  102714. (function (GLTF1) {
  102715. var GLTFLoaderExtension = /** @class */ (function () {
  102716. function GLTFLoaderExtension(name) {
  102717. this._name = name;
  102718. }
  102719. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  102720. get: function () {
  102721. return this._name;
  102722. },
  102723. enumerable: true,
  102724. configurable: true
  102725. });
  102726. /**
  102727. * Defines an override for loading the runtime
  102728. * Return true to stop further extensions from loading the runtime
  102729. */
  102730. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  102731. return false;
  102732. };
  102733. /**
  102734. * Defines an onverride for creating gltf runtime
  102735. * Return true to stop further extensions from creating the runtime
  102736. */
  102737. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  102738. return false;
  102739. };
  102740. /**
  102741. * Defines an override for loading buffers
  102742. * Return true to stop further extensions from loading this buffer
  102743. */
  102744. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102745. return false;
  102746. };
  102747. /**
  102748. * Defines an override for loading texture buffers
  102749. * Return true to stop further extensions from loading this texture data
  102750. */
  102751. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102752. return false;
  102753. };
  102754. /**
  102755. * Defines an override for creating textures
  102756. * Return true to stop further extensions from loading this texture
  102757. */
  102758. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102759. return false;
  102760. };
  102761. /**
  102762. * Defines an override for loading shader strings
  102763. * Return true to stop further extensions from loading this shader data
  102764. */
  102765. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102766. return false;
  102767. };
  102768. /**
  102769. * Defines an override for loading materials
  102770. * Return true to stop further extensions from loading this material
  102771. */
  102772. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102773. return false;
  102774. };
  102775. // ---------
  102776. // Utilities
  102777. // ---------
  102778. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  102779. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102780. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  102781. }, function () {
  102782. setTimeout(function () {
  102783. if (!onSuccess) {
  102784. return;
  102785. }
  102786. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  102787. });
  102788. });
  102789. };
  102790. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  102791. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102792. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  102793. }, function () {
  102794. setTimeout(function () {
  102795. onSuccess();
  102796. });
  102797. });
  102798. };
  102799. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102800. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102801. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  102802. }, function () {
  102803. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  102804. });
  102805. };
  102806. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  102807. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  102808. if (buffer) {
  102809. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  102810. }
  102811. }, onError);
  102812. };
  102813. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102814. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102815. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  102816. }, function () {
  102817. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  102818. });
  102819. };
  102820. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102821. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102822. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  102823. }, function () {
  102824. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  102825. });
  102826. };
  102827. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102828. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102829. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  102830. }, function () {
  102831. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  102832. });
  102833. };
  102834. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102835. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  102836. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  102837. }, function () {
  102838. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  102839. });
  102840. };
  102841. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  102842. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  102843. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  102844. if (func(loaderExtension)) {
  102845. return;
  102846. }
  102847. }
  102848. defaultFunc();
  102849. };
  102850. return GLTFLoaderExtension;
  102851. }());
  102852. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  102853. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102854. })(BABYLON || (BABYLON = {}));
  102855. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  102856. "use strict";
  102857. var BABYLON;
  102858. (function (BABYLON) {
  102859. var GLTF1;
  102860. (function (GLTF1) {
  102861. var BinaryExtensionBufferName = "binary_glTF";
  102862. ;
  102863. ;
  102864. var GLTFBinaryExtension = /** @class */ (function (_super) {
  102865. __extends(GLTFBinaryExtension, _super);
  102866. function GLTFBinaryExtension() {
  102867. return _super.call(this, "KHR_binary_glTF") || this;
  102868. }
  102869. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  102870. var extensionsUsed = data.json.extensionsUsed;
  102871. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  102872. return false;
  102873. }
  102874. this._bin = data.bin;
  102875. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  102876. return true;
  102877. };
  102878. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102879. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  102880. return false;
  102881. }
  102882. if (id !== BinaryExtensionBufferName) {
  102883. return false;
  102884. }
  102885. onSuccess(this._bin);
  102886. return true;
  102887. };
  102888. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102889. var texture = gltfRuntime.textures[id];
  102890. var source = gltfRuntime.images[texture.source];
  102891. if (!source.extensions || !(this.name in source.extensions)) {
  102892. return false;
  102893. }
  102894. var sourceExt = source.extensions[this.name];
  102895. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  102896. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  102897. onSuccess(buffer);
  102898. return true;
  102899. };
  102900. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102901. var shader = gltfRuntime.shaders[id];
  102902. if (!shader.extensions || !(this.name in shader.extensions)) {
  102903. return false;
  102904. }
  102905. var binaryExtensionShader = shader.extensions[this.name];
  102906. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  102907. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  102908. setTimeout(function () {
  102909. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  102910. onSuccess(shaderString);
  102911. });
  102912. return true;
  102913. };
  102914. return GLTFBinaryExtension;
  102915. }(GLTF1.GLTFLoaderExtension));
  102916. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  102917. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  102918. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102919. })(BABYLON || (BABYLON = {}));
  102920. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  102921. "use strict";
  102922. var BABYLON;
  102923. (function (BABYLON) {
  102924. var GLTF1;
  102925. (function (GLTF1) {
  102926. ;
  102927. ;
  102928. ;
  102929. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  102930. __extends(GLTFMaterialsCommonExtension, _super);
  102931. function GLTFMaterialsCommonExtension() {
  102932. return _super.call(this, "KHR_materials_common") || this;
  102933. }
  102934. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  102935. if (!gltfRuntime.extensions)
  102936. return false;
  102937. var extension = gltfRuntime.extensions[this.name];
  102938. if (!extension)
  102939. return false;
  102940. // Create lights
  102941. var lights = extension.lights;
  102942. if (lights) {
  102943. for (var thing in lights) {
  102944. var light = lights[thing];
  102945. switch (light.type) {
  102946. case "ambient":
  102947. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  102948. var ambient = light.ambient;
  102949. if (ambient) {
  102950. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  102951. }
  102952. break;
  102953. case "point":
  102954. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  102955. var point = light.point;
  102956. if (point) {
  102957. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  102958. }
  102959. break;
  102960. case "directional":
  102961. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  102962. var directional = light.directional;
  102963. if (directional) {
  102964. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  102965. }
  102966. break;
  102967. case "spot":
  102968. var spot = light.spot;
  102969. if (spot) {
  102970. 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);
  102971. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  102972. }
  102973. break;
  102974. default:
  102975. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  102976. break;
  102977. }
  102978. }
  102979. }
  102980. return false;
  102981. };
  102982. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102983. var material = gltfRuntime.materials[id];
  102984. if (!material || !material.extensions)
  102985. return false;
  102986. var extension = material.extensions[this.name];
  102987. if (!extension)
  102988. return false;
  102989. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  102990. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102991. if (extension.technique === "CONSTANT") {
  102992. standardMaterial.disableLighting = true;
  102993. }
  102994. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  102995. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  102996. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  102997. // Ambient
  102998. if (typeof extension.values.ambient === "string") {
  102999. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  103000. }
  103001. else {
  103002. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  103003. }
  103004. // Diffuse
  103005. if (typeof extension.values.diffuse === "string") {
  103006. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  103007. }
  103008. else {
  103009. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  103010. }
  103011. // Emission
  103012. if (typeof extension.values.emission === "string") {
  103013. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  103014. }
  103015. else {
  103016. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  103017. }
  103018. // Specular
  103019. if (typeof extension.values.specular === "string") {
  103020. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  103021. }
  103022. else {
  103023. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  103024. }
  103025. return true;
  103026. };
  103027. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  103028. // Create buffer from texture url
  103029. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103030. // Create texture from buffer
  103031. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  103032. }, onError);
  103033. };
  103034. return GLTFMaterialsCommonExtension;
  103035. }(GLTF1.GLTFLoaderExtension));
  103036. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  103037. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  103038. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103039. })(BABYLON || (BABYLON = {}));
  103040. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  103041. "use strict";
  103042. var BABYLON;
  103043. (function (BABYLON) {
  103044. var GLTF2;
  103045. (function (GLTF2) {
  103046. var ArrayItem = /** @class */ (function () {
  103047. function ArrayItem() {
  103048. }
  103049. ArrayItem.Assign = function (values) {
  103050. if (values) {
  103051. for (var index = 0; index < values.length; index++) {
  103052. values[index]._index = index;
  103053. }
  103054. }
  103055. };
  103056. return ArrayItem;
  103057. }());
  103058. GLTF2.ArrayItem = ArrayItem;
  103059. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  103060. })(BABYLON || (BABYLON = {}));
  103061. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  103062. "use strict";
  103063. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  103064. "use strict";
  103065. var BABYLON;
  103066. (function (BABYLON) {
  103067. var GLTF2;
  103068. (function (GLTF2) {
  103069. var GLTFLoader = /** @class */ (function () {
  103070. function GLTFLoader() {
  103071. this._completePromises = new Array();
  103072. this._disposed = false;
  103073. this._state = null;
  103074. this._extensions = {};
  103075. this._defaultSampler = {};
  103076. this._defaultBabylonMaterials = {};
  103077. this._requests = new Array();
  103078. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103079. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103080. this.compileMaterials = false;
  103081. this.useClipPlane = false;
  103082. this.compileShadowGenerators = false;
  103083. this.onDisposeObservable = new BABYLON.Observable();
  103084. this.onMeshLoadedObservable = new BABYLON.Observable();
  103085. this.onTextureLoadedObservable = new BABYLON.Observable();
  103086. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103087. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103088. this.onCompleteObservable = new BABYLON.Observable();
  103089. }
  103090. GLTFLoader._Register = function (name, factory) {
  103091. if (GLTFLoader._Factories[name]) {
  103092. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  103093. return;
  103094. }
  103095. GLTFLoader._Factories[name] = factory;
  103096. // Keep the order of registration so that extensions registered first are called first.
  103097. GLTFLoader._Names.push(name);
  103098. };
  103099. Object.defineProperty(GLTFLoader.prototype, "state", {
  103100. get: function () {
  103101. return this._state;
  103102. },
  103103. enumerable: true,
  103104. configurable: true
  103105. });
  103106. GLTFLoader.prototype.dispose = function () {
  103107. if (this._disposed) {
  103108. return;
  103109. }
  103110. this._disposed = true;
  103111. this.onDisposeObservable.notifyObservers(this);
  103112. this.onDisposeObservable.clear();
  103113. this._clear();
  103114. };
  103115. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103116. var _this = this;
  103117. return Promise.resolve().then(function () {
  103118. var nodes = null;
  103119. if (meshesNames) {
  103120. var nodeMap_1 = {};
  103121. if (_this._gltf.nodes) {
  103122. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  103123. var node = _a[_i];
  103124. if (node.name) {
  103125. nodeMap_1[node.name] = node;
  103126. }
  103127. }
  103128. }
  103129. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  103130. nodes = names.map(function (name) {
  103131. var node = nodeMap_1[name];
  103132. if (!node) {
  103133. throw new Error("Failed to find node '" + name + "'");
  103134. }
  103135. return node;
  103136. });
  103137. }
  103138. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  103139. return {
  103140. meshes: _this._getMeshes(),
  103141. particleSystems: [],
  103142. skeletons: _this._getSkeletons(),
  103143. animationGroups: _this._getAnimationGroups()
  103144. };
  103145. });
  103146. });
  103147. };
  103148. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103149. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  103150. };
  103151. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  103152. var _this = this;
  103153. return Promise.resolve().then(function () {
  103154. _this._loadExtensions();
  103155. _this._babylonScene = scene;
  103156. _this._rootUrl = rootUrl;
  103157. _this._progressCallback = onProgress;
  103158. _this._state = BABYLON.GLTFLoaderState.LOADING;
  103159. _this._loadData(data);
  103160. _this._checkExtensions();
  103161. var promises = new Array();
  103162. if (nodes) {
  103163. promises.push(_this._loadNodesAsync(nodes));
  103164. }
  103165. else {
  103166. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  103167. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  103168. }
  103169. if (_this.compileMaterials) {
  103170. promises.push(_this._compileMaterialsAsync());
  103171. }
  103172. if (_this.compileShadowGenerators) {
  103173. promises.push(_this._compileShadowGeneratorsAsync());
  103174. }
  103175. var resultPromise = Promise.all(promises).then(function () {
  103176. _this._state = BABYLON.GLTFLoaderState.READY;
  103177. _this._startAnimations();
  103178. });
  103179. resultPromise.then(function () {
  103180. _this._rootBabylonMesh.setEnabled(true);
  103181. BABYLON.Tools.SetImmediate(function () {
  103182. if (!_this._disposed) {
  103183. Promise.all(_this._completePromises).then(function () {
  103184. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  103185. _this.onCompleteObservable.notifyObservers(_this);
  103186. _this.onCompleteObservable.clear();
  103187. _this._clear();
  103188. }).catch(function (error) {
  103189. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103190. _this._clear();
  103191. });
  103192. }
  103193. });
  103194. });
  103195. return resultPromise;
  103196. }).catch(function (error) {
  103197. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103198. _this._clear();
  103199. throw error;
  103200. });
  103201. };
  103202. GLTFLoader.prototype._loadExtensions = function () {
  103203. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  103204. var name_1 = _a[_i];
  103205. var extension = GLTFLoader._Factories[name_1](this);
  103206. this._extensions[name_1] = extension;
  103207. this.onExtensionLoadedObservable.notifyObservers(extension);
  103208. }
  103209. this.onExtensionLoadedObservable.clear();
  103210. };
  103211. GLTFLoader.prototype._loadData = function (data) {
  103212. this._gltf = data.json;
  103213. this._setupData();
  103214. if (data.bin) {
  103215. var buffers = this._gltf.buffers;
  103216. if (buffers && buffers[0] && !buffers[0].uri) {
  103217. var binaryBuffer = buffers[0];
  103218. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  103219. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  103220. }
  103221. binaryBuffer._data = Promise.resolve(data.bin);
  103222. }
  103223. else {
  103224. BABYLON.Tools.Warn("Unexpected BIN chunk");
  103225. }
  103226. }
  103227. };
  103228. GLTFLoader.prototype._setupData = function () {
  103229. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  103230. GLTF2.ArrayItem.Assign(this._gltf.animations);
  103231. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  103232. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  103233. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  103234. GLTF2.ArrayItem.Assign(this._gltf.images);
  103235. GLTF2.ArrayItem.Assign(this._gltf.materials);
  103236. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  103237. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  103238. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  103239. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  103240. GLTF2.ArrayItem.Assign(this._gltf.skins);
  103241. GLTF2.ArrayItem.Assign(this._gltf.textures);
  103242. if (this._gltf.nodes) {
  103243. var nodeParents = {};
  103244. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  103245. var node = _a[_i];
  103246. if (node.children) {
  103247. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  103248. var index = _c[_b];
  103249. nodeParents[index] = node._index;
  103250. }
  103251. }
  103252. }
  103253. var rootNode = this._createRootNode();
  103254. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  103255. var node = _e[_d];
  103256. var parentIndex = nodeParents[node._index];
  103257. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  103258. }
  103259. }
  103260. };
  103261. GLTFLoader.prototype._checkExtensions = function () {
  103262. if (this._gltf.extensionsRequired) {
  103263. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  103264. var name_2 = _a[_i];
  103265. var extension = this._extensions[name_2];
  103266. if (!extension || !extension.enabled) {
  103267. throw new Error("Require extension " + name_2 + " is not available");
  103268. }
  103269. }
  103270. }
  103271. };
  103272. GLTFLoader.prototype._createRootNode = function () {
  103273. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  103274. this._rootBabylonMesh.setEnabled(false);
  103275. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  103276. switch (this.coordinateSystemMode) {
  103277. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  103278. if (!this._babylonScene.useRightHandedSystem) {
  103279. rootNode.rotation = [0, 1, 0, 0];
  103280. rootNode.scale = [1, 1, -1];
  103281. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  103282. }
  103283. break;
  103284. }
  103285. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  103286. this._babylonScene.useRightHandedSystem = true;
  103287. break;
  103288. }
  103289. default: {
  103290. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  103291. }
  103292. }
  103293. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  103294. return rootNode;
  103295. };
  103296. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  103297. var promises = new Array();
  103298. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  103299. var node = nodes_1[_i];
  103300. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103301. }
  103302. promises.push(this._loadAnimationsAsync());
  103303. return Promise.all(promises).then(function () { });
  103304. };
  103305. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  103306. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  103307. if (promise) {
  103308. return promise;
  103309. }
  103310. var promises = new Array();
  103311. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  103312. var index = _a[_i];
  103313. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  103314. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103315. }
  103316. promises.push(this._loadAnimationsAsync());
  103317. return Promise.all(promises).then(function () { });
  103318. };
  103319. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  103320. if (node._primitiveBabylonMeshes) {
  103321. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  103322. var babylonMesh = _a[_i];
  103323. callback(babylonMesh);
  103324. }
  103325. }
  103326. else {
  103327. callback(node._babylonMesh);
  103328. }
  103329. };
  103330. GLTFLoader.prototype._getMeshes = function () {
  103331. var meshes = new Array();
  103332. // Root mesh is always first.
  103333. meshes.push(this._rootBabylonMesh);
  103334. var nodes = this._gltf.nodes;
  103335. if (nodes) {
  103336. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  103337. var node = nodes_2[_i];
  103338. if (node._babylonMesh) {
  103339. meshes.push(node._babylonMesh);
  103340. }
  103341. if (node._primitiveBabylonMeshes) {
  103342. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  103343. var babylonMesh = _b[_a];
  103344. meshes.push(babylonMesh);
  103345. }
  103346. }
  103347. }
  103348. }
  103349. return meshes;
  103350. };
  103351. GLTFLoader.prototype._getSkeletons = function () {
  103352. var skeletons = new Array();
  103353. var skins = this._gltf.skins;
  103354. if (skins) {
  103355. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  103356. var skin = skins_1[_i];
  103357. if (skin._babylonSkeleton) {
  103358. skeletons.push(skin._babylonSkeleton);
  103359. }
  103360. }
  103361. }
  103362. return skeletons;
  103363. };
  103364. GLTFLoader.prototype._getAnimationGroups = function () {
  103365. var animationGroups = new Array();
  103366. var animations = this._gltf.animations;
  103367. if (animations) {
  103368. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  103369. var animation = animations_1[_i];
  103370. if (animation._babylonAnimationGroup) {
  103371. animationGroups.push(animation._babylonAnimationGroup);
  103372. }
  103373. }
  103374. }
  103375. return animationGroups;
  103376. };
  103377. GLTFLoader.prototype._startAnimations = function () {
  103378. switch (this.animationStartMode) {
  103379. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  103380. // do nothing
  103381. break;
  103382. }
  103383. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  103384. var babylonAnimationGroups = this._getAnimationGroups();
  103385. if (babylonAnimationGroups.length !== 0) {
  103386. babylonAnimationGroups[0].start(true);
  103387. }
  103388. break;
  103389. }
  103390. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  103391. var babylonAnimationGroups = this._getAnimationGroups();
  103392. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  103393. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  103394. babylonAnimationGroup.start(true);
  103395. }
  103396. break;
  103397. }
  103398. default: {
  103399. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  103400. return;
  103401. }
  103402. }
  103403. };
  103404. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  103405. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  103406. if (promise) {
  103407. return promise;
  103408. }
  103409. if (node._babylonMesh) {
  103410. throw new Error(context + ": Invalid recursive node hierarchy");
  103411. }
  103412. var promises = new Array();
  103413. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  103414. node._babylonMesh = babylonMesh;
  103415. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  103416. node._babylonAnimationTargets.push(babylonMesh);
  103417. GLTFLoader._LoadTransform(node, babylonMesh);
  103418. if (node.mesh != undefined) {
  103419. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  103420. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  103421. }
  103422. if (node.children) {
  103423. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  103424. var index = _a[_i];
  103425. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  103426. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  103427. }
  103428. }
  103429. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  103430. return Promise.all(promises).then(function () { });
  103431. };
  103432. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  103433. // TODO: instancing
  103434. var _this = this;
  103435. var promises = new Array();
  103436. var primitives = mesh.primitives;
  103437. if (!primitives || primitives.length === 0) {
  103438. throw new Error(context + ": Primitives are missing");
  103439. }
  103440. GLTF2.ArrayItem.Assign(primitives);
  103441. if (primitives.length === 1) {
  103442. var primitive = primitives[0];
  103443. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  103444. }
  103445. else {
  103446. node._primitiveBabylonMeshes = [];
  103447. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  103448. var primitive = primitives_1[_i];
  103449. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  103450. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  103451. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  103452. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  103453. }
  103454. }
  103455. if (node.skin != undefined) {
  103456. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  103457. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  103458. }
  103459. return Promise.all(promises).then(function () {
  103460. _this._forEachPrimitive(node, function (babylonMesh) {
  103461. babylonMesh._refreshBoundingInfo(true);
  103462. });
  103463. });
  103464. };
  103465. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  103466. var _this = this;
  103467. var promises = new Array();
  103468. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  103469. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  103470. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  103471. babylonGeometry.applyToMesh(babylonMesh);
  103472. });
  103473. }));
  103474. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  103475. if (primitive.material == undefined) {
  103476. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  103477. }
  103478. else {
  103479. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  103480. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  103481. babylonMesh.material = babylonMaterial;
  103482. }));
  103483. }
  103484. return Promise.all(promises).then(function () { });
  103485. };
  103486. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  103487. var _this = this;
  103488. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  103489. if (promise) {
  103490. return promise;
  103491. }
  103492. var attributes = primitive.attributes;
  103493. if (!attributes) {
  103494. throw new Error(context + ": Attributes are missing");
  103495. }
  103496. var promises = new Array();
  103497. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  103498. if (primitive.indices == undefined) {
  103499. babylonMesh.isUnIndexed = true;
  103500. }
  103501. else {
  103502. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  103503. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103504. babylonGeometry.setIndices(data);
  103505. }));
  103506. }
  103507. var loadAttribute = function (attribute, kind, callback) {
  103508. if (attributes[attribute] == undefined) {
  103509. return;
  103510. }
  103511. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  103512. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  103513. babylonMesh._delayInfo.push(kind);
  103514. }
  103515. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  103516. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  103517. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  103518. }));
  103519. if (callback) {
  103520. callback(accessor);
  103521. }
  103522. };
  103523. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  103524. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  103525. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  103526. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  103527. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  103528. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  103529. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  103530. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  103531. if (accessor.type === "VEC4" /* VEC4 */) {
  103532. babylonMesh.hasVertexAlpha = true;
  103533. }
  103534. });
  103535. return Promise.all(promises).then(function () {
  103536. return babylonGeometry;
  103537. });
  103538. };
  103539. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  103540. if (!primitive.targets) {
  103541. return;
  103542. }
  103543. if (node._numMorphTargets == undefined) {
  103544. node._numMorphTargets = primitive.targets.length;
  103545. }
  103546. else if (primitive.targets.length !== node._numMorphTargets) {
  103547. throw new Error(context + ": Primitives do not have the same number of targets");
  103548. }
  103549. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  103550. for (var index = 0; index < primitive.targets.length; index++) {
  103551. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  103552. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  103553. // TODO: tell the target whether it has positions, normals, tangents
  103554. }
  103555. };
  103556. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  103557. if (!primitive.targets) {
  103558. return Promise.resolve();
  103559. }
  103560. var promises = new Array();
  103561. var morphTargetManager = babylonMesh.morphTargetManager;
  103562. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  103563. var babylonMorphTarget = morphTargetManager.getTarget(index);
  103564. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  103565. }
  103566. return Promise.all(promises).then(function () { });
  103567. };
  103568. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  103569. var _this = this;
  103570. var promises = new Array();
  103571. var loadAttribute = function (attribute, kind, setData) {
  103572. if (attributes[attribute] == undefined) {
  103573. return;
  103574. }
  103575. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  103576. if (!babylonVertexBuffer) {
  103577. return;
  103578. }
  103579. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  103580. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103581. if (!(data instanceof Float32Array)) {
  103582. throw new Error(context + ": Morph target accessor must have float data");
  103583. }
  103584. setData(babylonVertexBuffer, data);
  103585. }));
  103586. };
  103587. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  103588. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103589. data[index] += value;
  103590. });
  103591. babylonMorphTarget.setPositions(data);
  103592. });
  103593. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  103594. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103595. data[index] += value;
  103596. });
  103597. babylonMorphTarget.setNormals(data);
  103598. });
  103599. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  103600. var dataIndex = 0;
  103601. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103602. // Tangent data for morph targets is stored as xyz delta.
  103603. // The vertexData.tangent is stored as xyzw.
  103604. // So we need to skip every fourth vertexData.tangent.
  103605. if (((index + 1) % 4) !== 0) {
  103606. data[dataIndex++] += value;
  103607. }
  103608. });
  103609. babylonMorphTarget.setTangents(data);
  103610. });
  103611. return Promise.all(promises).then(function () { });
  103612. };
  103613. GLTFLoader._LoadTransform = function (node, babylonNode) {
  103614. var position = BABYLON.Vector3.Zero();
  103615. var rotation = BABYLON.Quaternion.Identity();
  103616. var scaling = BABYLON.Vector3.One();
  103617. if (node.matrix) {
  103618. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  103619. matrix.decompose(scaling, rotation, position);
  103620. }
  103621. else {
  103622. if (node.translation)
  103623. position = BABYLON.Vector3.FromArray(node.translation);
  103624. if (node.rotation)
  103625. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  103626. if (node.scale)
  103627. scaling = BABYLON.Vector3.FromArray(node.scale);
  103628. }
  103629. babylonNode.position = position;
  103630. babylonNode.rotationQuaternion = rotation;
  103631. babylonNode.scaling = scaling;
  103632. };
  103633. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  103634. var _this = this;
  103635. var assignSkeleton = function () {
  103636. _this._forEachPrimitive(node, function (babylonMesh) {
  103637. babylonMesh.skeleton = skin._babylonSkeleton;
  103638. });
  103639. // Ignore the TRS of skinned nodes.
  103640. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  103641. node._babylonMesh.parent = _this._rootBabylonMesh;
  103642. node._babylonMesh.position = BABYLON.Vector3.Zero();
  103643. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  103644. node._babylonMesh.scaling = BABYLON.Vector3.One();
  103645. };
  103646. if (skin._loaded) {
  103647. return skin._loaded.then(function () {
  103648. assignSkeleton();
  103649. });
  103650. }
  103651. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  103652. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  103653. var skeletonId = "skeleton" + skin._index;
  103654. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  103655. skin._babylonSkeleton = babylonSkeleton;
  103656. _this._loadBones(context, skin, inverseBindMatricesData);
  103657. assignSkeleton();
  103658. }));
  103659. };
  103660. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  103661. if (skin.inverseBindMatrices == undefined) {
  103662. return Promise.resolve(null);
  103663. }
  103664. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  103665. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103666. return data;
  103667. });
  103668. };
  103669. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  103670. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  103671. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  103672. node._babylonAnimationTargets.push(babylonBone);
  103673. return babylonBone;
  103674. };
  103675. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  103676. var babylonBones = {};
  103677. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  103678. var index = _a[_i];
  103679. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  103680. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  103681. }
  103682. };
  103683. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  103684. var babylonBone = babylonBones[node._index];
  103685. if (babylonBone) {
  103686. return babylonBone;
  103687. }
  103688. var boneIndex = skin.joints.indexOf(node._index);
  103689. var baseMatrix = BABYLON.Matrix.Identity();
  103690. if (inverseBindMatricesData && boneIndex !== -1) {
  103691. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  103692. baseMatrix.invertToRef(baseMatrix);
  103693. }
  103694. var babylonParentBone = null;
  103695. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  103696. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  103697. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  103698. }
  103699. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  103700. babylonBones[node._index] = babylonBone;
  103701. return babylonBone;
  103702. };
  103703. GLTFLoader.prototype._getNodeMatrix = function (node) {
  103704. return node.matrix ?
  103705. BABYLON.Matrix.FromArray(node.matrix) :
  103706. 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());
  103707. };
  103708. GLTFLoader.prototype._loadAnimationsAsync = function () {
  103709. var animations = this._gltf.animations;
  103710. if (!animations) {
  103711. return Promise.resolve();
  103712. }
  103713. var promises = new Array();
  103714. for (var index = 0; index < animations.length; index++) {
  103715. var animation = animations[index];
  103716. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  103717. }
  103718. return Promise.all(promises).then(function () { });
  103719. };
  103720. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  103721. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  103722. animation._babylonAnimationGroup = babylonAnimationGroup;
  103723. var promises = new Array();
  103724. GLTF2.ArrayItem.Assign(animation.channels);
  103725. GLTF2.ArrayItem.Assign(animation.samplers);
  103726. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  103727. var channel = _a[_i];
  103728. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  103729. }
  103730. return Promise.all(promises).then(function () {
  103731. babylonAnimationGroup.normalize();
  103732. });
  103733. };
  103734. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  103735. var _this = this;
  103736. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  103737. if (!targetNode._babylonMesh) {
  103738. return Promise.resolve();
  103739. }
  103740. // Ignore animations targeting TRS of skinned nodes.
  103741. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  103742. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  103743. return Promise.resolve();
  103744. }
  103745. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  103746. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  103747. var targetPath;
  103748. var animationType;
  103749. switch (channel.target.path) {
  103750. case "translation" /* TRANSLATION */: {
  103751. targetPath = "position";
  103752. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  103753. break;
  103754. }
  103755. case "rotation" /* ROTATION */: {
  103756. targetPath = "rotationQuaternion";
  103757. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  103758. break;
  103759. }
  103760. case "scale" /* SCALE */: {
  103761. targetPath = "scaling";
  103762. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  103763. break;
  103764. }
  103765. case "weights" /* WEIGHTS */: {
  103766. targetPath = "influence";
  103767. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  103768. break;
  103769. }
  103770. default: {
  103771. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  103772. }
  103773. }
  103774. var outputBufferOffset = 0;
  103775. var getNextOutputValue;
  103776. switch (targetPath) {
  103777. case "position": {
  103778. getNextOutputValue = function () {
  103779. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  103780. outputBufferOffset += 3;
  103781. return value;
  103782. };
  103783. break;
  103784. }
  103785. case "rotationQuaternion": {
  103786. getNextOutputValue = function () {
  103787. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  103788. outputBufferOffset += 4;
  103789. return value;
  103790. };
  103791. break;
  103792. }
  103793. case "scaling": {
  103794. getNextOutputValue = function () {
  103795. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  103796. outputBufferOffset += 3;
  103797. return value;
  103798. };
  103799. break;
  103800. }
  103801. case "influence": {
  103802. getNextOutputValue = function () {
  103803. var value = new Array(targetNode._numMorphTargets);
  103804. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  103805. value[i] = data.output[outputBufferOffset++];
  103806. }
  103807. return value;
  103808. };
  103809. break;
  103810. }
  103811. }
  103812. var getNextKey;
  103813. switch (data.interpolation) {
  103814. case "STEP" /* STEP */: {
  103815. getNextKey = function (frameIndex) { return ({
  103816. frame: data.input[frameIndex],
  103817. value: getNextOutputValue(),
  103818. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  103819. }); };
  103820. break;
  103821. }
  103822. case "LINEAR" /* LINEAR */: {
  103823. getNextKey = function (frameIndex) { return ({
  103824. frame: data.input[frameIndex],
  103825. value: getNextOutputValue()
  103826. }); };
  103827. break;
  103828. }
  103829. case "CUBICSPLINE" /* CUBICSPLINE */: {
  103830. getNextKey = function (frameIndex) { return ({
  103831. frame: data.input[frameIndex],
  103832. inTangent: getNextOutputValue(),
  103833. value: getNextOutputValue(),
  103834. outTangent: getNextOutputValue()
  103835. }); };
  103836. break;
  103837. }
  103838. }
  103839. var keys = new Array(data.input.length);
  103840. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  103841. keys[frameIndex] = getNextKey(frameIndex);
  103842. }
  103843. if (targetPath === "influence") {
  103844. var _loop_1 = function (targetIndex) {
  103845. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  103846. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  103847. babylonAnimation.setKeys(keys.map(function (key) { return ({
  103848. frame: key.frame,
  103849. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  103850. value: key.value[targetIndex],
  103851. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  103852. }); }));
  103853. var morphTargets = new Array();
  103854. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  103855. morphTargets.push(babylonMesh.morphTargetManager.getTarget(targetIndex));
  103856. });
  103857. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  103858. };
  103859. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  103860. _loop_1(targetIndex);
  103861. }
  103862. }
  103863. else {
  103864. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  103865. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  103866. babylonAnimation.setKeys(keys);
  103867. if (targetNode._babylonAnimationTargets) {
  103868. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  103869. }
  103870. }
  103871. });
  103872. };
  103873. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  103874. if (sampler._data) {
  103875. return sampler._data;
  103876. }
  103877. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  103878. switch (interpolation) {
  103879. case "STEP" /* STEP */:
  103880. case "LINEAR" /* LINEAR */:
  103881. case "CUBICSPLINE" /* CUBICSPLINE */: {
  103882. break;
  103883. }
  103884. default: {
  103885. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  103886. }
  103887. }
  103888. var inputData;
  103889. var outputData;
  103890. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  103891. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  103892. sampler._data = Promise.all([
  103893. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  103894. inputData = data;
  103895. }),
  103896. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  103897. outputData = data;
  103898. })
  103899. ]).then(function () {
  103900. return {
  103901. input: inputData,
  103902. interpolation: interpolation,
  103903. output: outputData,
  103904. };
  103905. });
  103906. return sampler._data;
  103907. };
  103908. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  103909. if (buffer._data) {
  103910. return buffer._data;
  103911. }
  103912. if (!buffer.uri) {
  103913. throw new Error(context + ": Uri is missing");
  103914. }
  103915. buffer._data = this._loadUriAsync(context, buffer.uri);
  103916. return buffer._data;
  103917. };
  103918. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  103919. if (bufferView._data) {
  103920. return bufferView._data;
  103921. }
  103922. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  103923. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  103924. try {
  103925. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  103926. }
  103927. catch (e) {
  103928. throw new Error(context + ": " + e.message);
  103929. }
  103930. });
  103931. return bufferView._data;
  103932. };
  103933. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  103934. if (accessor.sparse) {
  103935. throw new Error(context + ": Sparse accessors are not currently supported");
  103936. }
  103937. if (accessor._data) {
  103938. return accessor._data;
  103939. }
  103940. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  103941. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  103942. var buffer = data.buffer;
  103943. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  103944. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  103945. try {
  103946. switch (accessor.componentType) {
  103947. case 5120 /* BYTE */: {
  103948. return new Int8Array(buffer, byteOffset, length);
  103949. }
  103950. case 5121 /* UNSIGNED_BYTE */: {
  103951. return new Uint8Array(buffer, byteOffset, length);
  103952. }
  103953. case 5122 /* SHORT */: {
  103954. return new Int16Array(buffer, byteOffset, length);
  103955. }
  103956. case 5123 /* UNSIGNED_SHORT */: {
  103957. return new Uint16Array(buffer, byteOffset, length);
  103958. }
  103959. case 5125 /* UNSIGNED_INT */: {
  103960. return new Uint32Array(buffer, byteOffset, length);
  103961. }
  103962. case 5126 /* FLOAT */: {
  103963. return new Float32Array(buffer, byteOffset, length);
  103964. }
  103965. default: {
  103966. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  103967. }
  103968. }
  103969. }
  103970. catch (e) {
  103971. throw new Error(context + ": " + e);
  103972. }
  103973. });
  103974. return accessor._data;
  103975. };
  103976. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  103977. var _this = this;
  103978. if (bufferView._babylonBuffer) {
  103979. return bufferView._babylonBuffer;
  103980. }
  103981. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  103982. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  103983. });
  103984. return bufferView._babylonBuffer;
  103985. };
  103986. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  103987. var _this = this;
  103988. if (accessor.sparse) {
  103989. throw new Error(context + ": Sparse accessors are not currently supported");
  103990. }
  103991. if (accessor._babylonVertexBuffer) {
  103992. return accessor._babylonVertexBuffer;
  103993. }
  103994. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  103995. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  103996. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  103997. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  103998. });
  103999. return accessor._babylonVertexBuffer;
  104000. };
  104001. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  104002. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  104003. if (!babylonMaterial) {
  104004. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  104005. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104006. babylonMaterial.metallic = 1;
  104007. babylonMaterial.roughness = 1;
  104008. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104009. }
  104010. return babylonMaterial;
  104011. };
  104012. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  104013. var promises = new Array();
  104014. // Ensure metallic workflow
  104015. babylonMaterial.metallic = 1;
  104016. babylonMaterial.roughness = 1;
  104017. var properties = material.pbrMetallicRoughness;
  104018. if (properties) {
  104019. if (properties.baseColorFactor) {
  104020. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  104021. babylonMaterial.alpha = properties.baseColorFactor[3];
  104022. }
  104023. else {
  104024. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104025. }
  104026. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  104027. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  104028. if (properties.baseColorTexture) {
  104029. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  104030. babylonMaterial.albedoTexture = texture;
  104031. }));
  104032. }
  104033. if (properties.metallicRoughnessTexture) {
  104034. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  104035. babylonMaterial.metallicTexture = texture;
  104036. }));
  104037. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  104038. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  104039. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  104040. }
  104041. }
  104042. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104043. return Promise.all(promises).then(function () { });
  104044. };
  104045. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104046. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  104047. if (promise) {
  104048. return promise;
  104049. }
  104050. material._babylonData = material._babylonData || {};
  104051. var babylonData = material._babylonData[babylonDrawMode];
  104052. if (!babylonData) {
  104053. var promises = new Array();
  104054. var name_3 = material.name || "materialSG_" + material._index;
  104055. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  104056. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  104057. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  104058. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104059. babylonData = {
  104060. material: babylonMaterial,
  104061. meshes: [],
  104062. loaded: Promise.all(promises).then(function () { })
  104063. };
  104064. material._babylonData[babylonDrawMode] = babylonData;
  104065. }
  104066. babylonData.meshes.push(babylonMesh);
  104067. assign(babylonData.material);
  104068. return babylonData.loaded;
  104069. };
  104070. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  104071. var babylonMaterial = new type(name, this._babylonScene);
  104072. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  104073. babylonMaterial.fillMode = drawMode;
  104074. return babylonMaterial;
  104075. };
  104076. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  104077. var promises = new Array();
  104078. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  104079. if (material.doubleSided) {
  104080. babylonMaterial.backFaceCulling = false;
  104081. babylonMaterial.twoSidedLighting = true;
  104082. }
  104083. if (material.normalTexture) {
  104084. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  104085. babylonMaterial.bumpTexture = texture;
  104086. }));
  104087. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  104088. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  104089. if (material.normalTexture.scale != undefined) {
  104090. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  104091. }
  104092. }
  104093. if (material.occlusionTexture) {
  104094. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  104095. babylonMaterial.ambientTexture = texture;
  104096. }));
  104097. babylonMaterial.useAmbientInGrayScale = true;
  104098. if (material.occlusionTexture.strength != undefined) {
  104099. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  104100. }
  104101. }
  104102. if (material.emissiveTexture) {
  104103. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  104104. babylonMaterial.emissiveTexture = texture;
  104105. }));
  104106. }
  104107. return Promise.all(promises).then(function () { });
  104108. };
  104109. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  104110. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  104111. switch (alphaMode) {
  104112. case "OPAQUE" /* OPAQUE */: {
  104113. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104114. break;
  104115. }
  104116. case "MASK" /* MASK */: {
  104117. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  104118. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  104119. if (babylonMaterial.albedoTexture) {
  104120. babylonMaterial.albedoTexture.hasAlpha = true;
  104121. }
  104122. break;
  104123. }
  104124. case "BLEND" /* BLEND */: {
  104125. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  104126. if (babylonMaterial.albedoTexture) {
  104127. babylonMaterial.albedoTexture.hasAlpha = true;
  104128. babylonMaterial.useAlphaFromAlbedoTexture = true;
  104129. }
  104130. break;
  104131. }
  104132. default: {
  104133. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  104134. }
  104135. }
  104136. };
  104137. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  104138. var _this = this;
  104139. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  104140. context = "#/textures/" + textureInfo.index;
  104141. var promises = new Array();
  104142. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  104143. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  104144. var deferred = new BABYLON.Deferred();
  104145. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  104146. if (!_this._disposed) {
  104147. deferred.resolve();
  104148. }
  104149. }, function (message, exception) {
  104150. if (!_this._disposed) {
  104151. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  104152. }
  104153. });
  104154. promises.push(deferred.promise);
  104155. babylonTexture.name = texture.name || "texture" + texture._index;
  104156. babylonTexture.wrapU = samplerData.wrapU;
  104157. babylonTexture.wrapV = samplerData.wrapV;
  104158. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  104159. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  104160. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  104161. babylonTexture.updateURL(objectURL);
  104162. }));
  104163. assign(babylonTexture);
  104164. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  104165. return Promise.all(promises).then(function () { });
  104166. };
  104167. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  104168. if (!sampler._data) {
  104169. sampler._data = {
  104170. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  104171. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  104172. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  104173. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  104174. };
  104175. }
  104176. ;
  104177. return sampler._data;
  104178. };
  104179. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  104180. if (image._objectURL) {
  104181. return image._objectURL;
  104182. }
  104183. var promise;
  104184. if (image.uri) {
  104185. promise = this._loadUriAsync(context, image.uri);
  104186. }
  104187. else {
  104188. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  104189. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  104190. }
  104191. image._objectURL = promise.then(function (data) {
  104192. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  104193. });
  104194. return image._objectURL;
  104195. };
  104196. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  104197. var _this = this;
  104198. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  104199. if (promise) {
  104200. return promise;
  104201. }
  104202. if (!GLTFLoader._ValidateUri(uri)) {
  104203. throw new Error(context + ": Uri '" + uri + "' is invalid");
  104204. }
  104205. if (BABYLON.Tools.IsBase64(uri)) {
  104206. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  104207. }
  104208. return new Promise(function (resolve, reject) {
  104209. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  104210. if (!_this._disposed) {
  104211. resolve(new Uint8Array(data));
  104212. }
  104213. }, function (event) {
  104214. if (!_this._disposed) {
  104215. try {
  104216. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  104217. request._lengthComputable = event.lengthComputable;
  104218. request._loaded = event.loaded;
  104219. request._total = event.total;
  104220. _this._onProgress();
  104221. }
  104222. }
  104223. catch (e) {
  104224. reject(e);
  104225. }
  104226. }
  104227. }, _this._babylonScene.database, true, function (request, exception) {
  104228. if (!_this._disposed) {
  104229. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  104230. }
  104231. });
  104232. _this._requests.push(request);
  104233. });
  104234. };
  104235. GLTFLoader.prototype._onProgress = function () {
  104236. if (!this._progressCallback) {
  104237. return;
  104238. }
  104239. var lengthComputable = true;
  104240. var loaded = 0;
  104241. var total = 0;
  104242. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  104243. var request = _a[_i];
  104244. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  104245. return;
  104246. }
  104247. lengthComputable = lengthComputable && request._lengthComputable;
  104248. loaded += request._loaded;
  104249. total += request._total;
  104250. }
  104251. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  104252. };
  104253. GLTFLoader._GetProperty = function (context, array, index) {
  104254. if (!array || index == undefined || !array[index]) {
  104255. throw new Error(context + ": Failed to find index (" + index + ")");
  104256. }
  104257. return array[index];
  104258. };
  104259. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  104260. // Set defaults if undefined
  104261. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  104262. switch (mode) {
  104263. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  104264. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  104265. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104266. default:
  104267. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  104268. return BABYLON.Texture.WRAP_ADDRESSMODE;
  104269. }
  104270. };
  104271. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  104272. // Set defaults if undefined
  104273. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  104274. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  104275. if (magFilter === 9729 /* LINEAR */) {
  104276. switch (minFilter) {
  104277. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  104278. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  104279. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  104280. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  104281. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  104282. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104283. default:
  104284. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  104285. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104286. }
  104287. }
  104288. else {
  104289. if (magFilter !== 9728 /* NEAREST */) {
  104290. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  104291. }
  104292. switch (minFilter) {
  104293. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  104294. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  104295. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  104296. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  104297. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  104298. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  104299. default:
  104300. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  104301. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  104302. }
  104303. }
  104304. };
  104305. GLTFLoader._GetNumComponents = function (context, type) {
  104306. switch (type) {
  104307. case "SCALAR": return 1;
  104308. case "VEC2": return 2;
  104309. case "VEC3": return 3;
  104310. case "VEC4": return 4;
  104311. case "MAT2": return 4;
  104312. case "MAT3": return 9;
  104313. case "MAT4": return 16;
  104314. }
  104315. throw new Error(context + ": Invalid type (" + type + ")");
  104316. };
  104317. GLTFLoader._ValidateUri = function (uri) {
  104318. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  104319. };
  104320. GLTFLoader._GetDrawMode = function (context, mode) {
  104321. if (mode == undefined) {
  104322. mode = 4 /* TRIANGLES */;
  104323. }
  104324. switch (mode) {
  104325. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  104326. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  104327. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  104328. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  104329. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  104330. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  104331. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  104332. }
  104333. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  104334. };
  104335. GLTFLoader.prototype._compileMaterialsAsync = function () {
  104336. var promises = new Array();
  104337. if (this._gltf.materials) {
  104338. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  104339. var material = _a[_i];
  104340. if (material._babylonData) {
  104341. for (var babylonDrawMode in material._babylonData) {
  104342. var babylonData = material._babylonData[babylonDrawMode];
  104343. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  104344. var babylonMesh = _c[_b];
  104345. // Ensure nonUniformScaling is set if necessary.
  104346. babylonMesh.computeWorldMatrix(true);
  104347. var babylonMaterial = babylonData.material;
  104348. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  104349. if (this.useClipPlane) {
  104350. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  104351. }
  104352. }
  104353. }
  104354. }
  104355. }
  104356. }
  104357. return Promise.all(promises).then(function () { });
  104358. };
  104359. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  104360. var promises = new Array();
  104361. var lights = this._babylonScene.lights;
  104362. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  104363. var light = lights_1[_i];
  104364. var generator = light.getShadowGenerator();
  104365. if (generator) {
  104366. promises.push(generator.forceCompilationAsync());
  104367. }
  104368. }
  104369. return Promise.all(promises).then(function () { });
  104370. };
  104371. GLTFLoader.prototype._clear = function () {
  104372. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  104373. var request = _a[_i];
  104374. request.abort();
  104375. }
  104376. this._requests.length = 0;
  104377. if (this._gltf && this._gltf.images) {
  104378. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  104379. var image = _c[_b];
  104380. if (image._objectURL) {
  104381. image._objectURL.then(function (value) {
  104382. URL.revokeObjectURL(value);
  104383. });
  104384. image._objectURL = undefined;
  104385. }
  104386. }
  104387. }
  104388. delete this._gltf;
  104389. delete this._babylonScene;
  104390. this._completePromises.length = 0;
  104391. for (var name_4 in this._extensions) {
  104392. this._extensions[name_4].dispose();
  104393. }
  104394. this._extensions = {};
  104395. delete this._rootBabylonMesh;
  104396. delete this._progressCallback;
  104397. this.onMeshLoadedObservable.clear();
  104398. this.onTextureLoadedObservable.clear();
  104399. this.onMaterialLoadedObservable.clear();
  104400. };
  104401. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  104402. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  104403. var name_5 = _a[_i];
  104404. var extension = this._extensions[name_5];
  104405. if (extension.enabled) {
  104406. var promise = actionAsync(extension);
  104407. if (promise) {
  104408. return promise;
  104409. }
  104410. }
  104411. }
  104412. return null;
  104413. };
  104414. GLTFLoader._Names = new Array();
  104415. GLTFLoader._Factories = {};
  104416. return GLTFLoader;
  104417. }());
  104418. GLTF2.GLTFLoader = GLTFLoader;
  104419. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  104420. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104421. })(BABYLON || (BABYLON = {}));
  104422. //# sourceMappingURL=babylon.glTFLoader.js.map
  104423. "use strict";
  104424. var BABYLON;
  104425. (function (BABYLON) {
  104426. var GLTF2;
  104427. (function (GLTF2) {
  104428. var GLTFLoaderExtension = /** @class */ (function () {
  104429. function GLTFLoaderExtension(loader) {
  104430. this.enabled = true;
  104431. this._loader = loader;
  104432. }
  104433. GLTFLoaderExtension.prototype.dispose = function () {
  104434. delete this._loader;
  104435. };
  104436. // #region Overridable Methods
  104437. /** Override this method to modify the default behavior for loading scenes. */
  104438. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  104439. /** Override this method to modify the default behavior for loading nodes. */
  104440. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  104441. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  104442. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  104443. /** Override this method to modify the default behavior for loading materials. */
  104444. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  104445. /** Override this method to modify the default behavior for loading uris. */
  104446. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  104447. // #endregion
  104448. /** Helper method called by a loader extension to load an glTF extension. */
  104449. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  104450. if (!property.extensions) {
  104451. return null;
  104452. }
  104453. var extensions = property.extensions;
  104454. var extension = extensions[this.name];
  104455. if (!extension) {
  104456. return null;
  104457. }
  104458. // Clear out the extension before executing the action to avoid recursing into the same property.
  104459. delete extensions[this.name];
  104460. try {
  104461. return actionAsync(context + "/extensions/" + this.name, extension);
  104462. }
  104463. finally {
  104464. // Restore the extension after executing the action.
  104465. extensions[this.name] = extension;
  104466. }
  104467. };
  104468. /** Helper method called by the loader to allow extensions to override loading scenes. */
  104469. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  104470. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  104471. };
  104472. /** Helper method called by the loader to allow extensions to override loading nodes. */
  104473. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  104474. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  104475. };
  104476. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  104477. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  104478. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  104479. };
  104480. /** Helper method called by the loader to allow extensions to override loading materials. */
  104481. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  104482. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  104483. };
  104484. /** Helper method called by the loader to allow extensions to override loading uris. */
  104485. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  104486. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  104487. };
  104488. return GLTFLoaderExtension;
  104489. }());
  104490. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  104491. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104492. })(BABYLON || (BABYLON = {}));
  104493. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  104494. "use strict";
  104495. var BABYLON;
  104496. (function (BABYLON) {
  104497. var GLTF2;
  104498. (function (GLTF2) {
  104499. var Extensions;
  104500. (function (Extensions) {
  104501. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  104502. var NAME = "MSFT_lod";
  104503. var MSFT_lod = /** @class */ (function (_super) {
  104504. __extends(MSFT_lod, _super);
  104505. function MSFT_lod() {
  104506. var _this = _super !== null && _super.apply(this, arguments) || this;
  104507. _this.name = NAME;
  104508. /**
  104509. * Maximum number of LODs to load, starting from the lowest LOD.
  104510. */
  104511. _this.maxLODsToLoad = Number.MAX_VALUE;
  104512. _this._loadingNodeLOD = null;
  104513. _this._loadNodeSignals = {};
  104514. _this._loadingMaterialLOD = null;
  104515. _this._loadMaterialSignals = {};
  104516. return _this;
  104517. }
  104518. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  104519. var _this = this;
  104520. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  104521. var firstPromise;
  104522. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  104523. var _loop_1 = function (indexLOD) {
  104524. var nodeLOD = nodeLODs[indexLOD];
  104525. if (indexLOD !== 0) {
  104526. _this._loadingNodeLOD = nodeLOD;
  104527. if (!_this._loadNodeSignals[nodeLOD._index]) {
  104528. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  104529. }
  104530. }
  104531. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  104532. if (indexLOD !== 0) {
  104533. var previousNodeLOD = nodeLODs[indexLOD - 1];
  104534. if (previousNodeLOD._babylonMesh) {
  104535. previousNodeLOD._babylonMesh.dispose(false, true);
  104536. delete previousNodeLOD._babylonMesh;
  104537. }
  104538. }
  104539. if (indexLOD !== nodeLODs.length - 1) {
  104540. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  104541. if (_this._loadNodeSignals[nodeIndex]) {
  104542. _this._loadNodeSignals[nodeIndex].resolve();
  104543. delete _this._loadNodeSignals[nodeIndex];
  104544. }
  104545. }
  104546. });
  104547. if (indexLOD === 0) {
  104548. firstPromise = promise;
  104549. }
  104550. else {
  104551. _this._loader._completePromises.push(promise);
  104552. _this._loadingNodeLOD = null;
  104553. }
  104554. };
  104555. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  104556. _loop_1(indexLOD);
  104557. }
  104558. return firstPromise;
  104559. });
  104560. };
  104561. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104562. var _this = this;
  104563. // Don't load material LODs if already loading a node LOD.
  104564. if (this._loadingNodeLOD) {
  104565. return null;
  104566. }
  104567. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  104568. var firstPromise;
  104569. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  104570. var _loop_2 = function (indexLOD) {
  104571. var materialLOD = materialLODs[indexLOD];
  104572. if (indexLOD !== 0) {
  104573. _this._loadingMaterialLOD = materialLOD;
  104574. if (!_this._loadMaterialSignals[materialLOD._index]) {
  104575. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  104576. }
  104577. }
  104578. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  104579. if (indexLOD !== 0) {
  104580. var babylonDataLOD = materialLOD._babylonData;
  104581. assign(babylonDataLOD[babylonDrawMode].material);
  104582. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  104583. if (previousBabylonDataLOD[babylonDrawMode]) {
  104584. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  104585. delete previousBabylonDataLOD[babylonDrawMode];
  104586. }
  104587. }
  104588. if (indexLOD !== materialLODs.length - 1) {
  104589. var materialIndex = materialLODs[indexLOD + 1]._index;
  104590. if (_this._loadMaterialSignals[materialIndex]) {
  104591. _this._loadMaterialSignals[materialIndex].resolve();
  104592. delete _this._loadMaterialSignals[materialIndex];
  104593. }
  104594. }
  104595. });
  104596. if (indexLOD === 0) {
  104597. firstPromise = promise;
  104598. }
  104599. else {
  104600. _this._loader._completePromises.push(promise);
  104601. _this._loadingMaterialLOD = null;
  104602. }
  104603. };
  104604. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  104605. _loop_2(indexLOD);
  104606. }
  104607. return firstPromise;
  104608. });
  104609. };
  104610. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  104611. var _this = this;
  104612. // Defer the loading of uris if loading a material or node LOD.
  104613. if (this._loadingMaterialLOD) {
  104614. var index = this._loadingMaterialLOD._index;
  104615. return this._loadMaterialSignals[index].promise.then(function () {
  104616. return _this._loader._loadUriAsync(context, uri);
  104617. });
  104618. }
  104619. else if (this._loadingNodeLOD) {
  104620. var index = this._loadingNodeLOD._index;
  104621. return this._loadNodeSignals[index].promise.then(function () {
  104622. return _this._loader._loadUriAsync(context, uri);
  104623. });
  104624. }
  104625. return null;
  104626. };
  104627. /**
  104628. * Gets an array of LOD properties from lowest to highest.
  104629. */
  104630. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  104631. if (this.maxLODsToLoad <= 0) {
  104632. throw new Error("maxLODsToLoad must be greater than zero");
  104633. }
  104634. var properties = new Array();
  104635. for (var i = ids.length - 1; i >= 0; i--) {
  104636. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  104637. if (properties.length === this.maxLODsToLoad) {
  104638. return properties;
  104639. }
  104640. }
  104641. properties.push(property);
  104642. return properties;
  104643. };
  104644. return MSFT_lod;
  104645. }(GLTF2.GLTFLoaderExtension));
  104646. Extensions.MSFT_lod = MSFT_lod;
  104647. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  104648. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104649. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104650. })(BABYLON || (BABYLON = {}));
  104651. //# sourceMappingURL=MSFT_lod.js.map
  104652. "use strict";
  104653. var BABYLON;
  104654. (function (BABYLON) {
  104655. var GLTF2;
  104656. (function (GLTF2) {
  104657. var Extensions;
  104658. (function (Extensions) {
  104659. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  104660. var NAME = "KHR_draco_mesh_compression";
  104661. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  104662. __extends(KHR_draco_mesh_compression, _super);
  104663. function KHR_draco_mesh_compression(loader) {
  104664. var _this = _super.call(this, loader) || this;
  104665. _this.name = NAME;
  104666. _this._dracoCompression = null;
  104667. // Disable extension if decoder is not available.
  104668. if (!BABYLON.DracoCompression.DecoderAvailable) {
  104669. _this.enabled = false;
  104670. }
  104671. return _this;
  104672. }
  104673. KHR_draco_mesh_compression.prototype.dispose = function () {
  104674. if (this._dracoCompression) {
  104675. this._dracoCompression.dispose();
  104676. }
  104677. _super.prototype.dispose.call(this);
  104678. };
  104679. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  104680. var _this = this;
  104681. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  104682. if (primitive.mode != undefined) {
  104683. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  104684. primitive.mode !== 4 /* TRIANGLES */) {
  104685. throw new Error(context + ": Unsupported mode " + primitive.mode);
  104686. }
  104687. // TODO: handle triangle strips
  104688. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  104689. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  104690. }
  104691. }
  104692. var attributes = {};
  104693. var loadAttribute = function (name, kind) {
  104694. var uniqueId = extension.attributes[name];
  104695. if (uniqueId == undefined) {
  104696. return;
  104697. }
  104698. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  104699. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  104700. babylonMesh._delayInfo.push(kind);
  104701. }
  104702. attributes[kind] = uniqueId;
  104703. };
  104704. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  104705. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  104706. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  104707. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  104708. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  104709. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  104710. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  104711. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  104712. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  104713. if (!bufferView._dracoBabylonGeometry) {
  104714. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  104715. if (!_this._dracoCompression) {
  104716. _this._dracoCompression = new BABYLON.DracoCompression();
  104717. }
  104718. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  104719. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  104720. babylonVertexData.applyToGeometry(babylonGeometry);
  104721. return babylonGeometry;
  104722. }).catch(function (error) {
  104723. throw new Error(context + ": " + error.message);
  104724. });
  104725. });
  104726. }
  104727. return bufferView._dracoBabylonGeometry;
  104728. });
  104729. };
  104730. return KHR_draco_mesh_compression;
  104731. }(GLTF2.GLTFLoaderExtension));
  104732. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  104733. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  104734. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104735. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104736. })(BABYLON || (BABYLON = {}));
  104737. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  104738. "use strict";
  104739. var BABYLON;
  104740. (function (BABYLON) {
  104741. var GLTF2;
  104742. (function (GLTF2) {
  104743. var Extensions;
  104744. (function (Extensions) {
  104745. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  104746. var NAME = "KHR_materials_pbrSpecularGlossiness";
  104747. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  104748. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  104749. function KHR_materials_pbrSpecularGlossiness() {
  104750. var _this = _super !== null && _super.apply(this, arguments) || this;
  104751. _this.name = NAME;
  104752. return _this;
  104753. }
  104754. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104755. var _this = this;
  104756. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  104757. material._babylonData = material._babylonData || {};
  104758. var babylonData = material._babylonData[babylonDrawMode];
  104759. if (!babylonData) {
  104760. var promises = new Array();
  104761. var name_1 = material.name || "materialSG_" + material._index;
  104762. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  104763. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  104764. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  104765. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104766. babylonData = {
  104767. material: babylonMaterial,
  104768. meshes: [],
  104769. loaded: Promise.all(promises).then(function () { })
  104770. };
  104771. material._babylonData[babylonDrawMode] = babylonData;
  104772. }
  104773. babylonData.meshes.push(babylonMesh);
  104774. assign(babylonData.material);
  104775. return babylonData.loaded;
  104776. });
  104777. };
  104778. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  104779. var promises = new Array();
  104780. if (properties.diffuseFactor) {
  104781. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  104782. babylonMaterial.alpha = properties.diffuseFactor[3];
  104783. }
  104784. else {
  104785. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104786. }
  104787. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  104788. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  104789. if (properties.diffuseTexture) {
  104790. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  104791. babylonMaterial.albedoTexture = texture;
  104792. }));
  104793. }
  104794. if (properties.specularGlossinessTexture) {
  104795. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  104796. babylonMaterial.reflectivityTexture = texture;
  104797. }));
  104798. babylonMaterial.reflectivityTexture.hasAlpha = true;
  104799. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  104800. }
  104801. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104802. return Promise.all(promises).then(function () { });
  104803. };
  104804. return KHR_materials_pbrSpecularGlossiness;
  104805. }(GLTF2.GLTFLoaderExtension));
  104806. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  104807. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  104808. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104809. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104810. })(BABYLON || (BABYLON = {}));
  104811. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  104812. "use strict";
  104813. var BABYLON;
  104814. (function (BABYLON) {
  104815. var GLTF2;
  104816. (function (GLTF2) {
  104817. var Extensions;
  104818. (function (Extensions) {
  104819. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  104820. var NAME = "KHR_materials_unlit";
  104821. var KHR_materials_unlit = /** @class */ (function (_super) {
  104822. __extends(KHR_materials_unlit, _super);
  104823. function KHR_materials_unlit() {
  104824. var _this = _super !== null && _super.apply(this, arguments) || this;
  104825. _this.name = NAME;
  104826. return _this;
  104827. }
  104828. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104829. var _this = this;
  104830. return this._loadExtensionAsync(context, material, function () {
  104831. material._babylonData = material._babylonData || {};
  104832. var babylonData = material._babylonData[babylonDrawMode];
  104833. if (!babylonData) {
  104834. var name_1 = material.name || "materialUnlit_" + material._index;
  104835. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  104836. babylonMaterial.unlit = true;
  104837. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  104838. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104839. babylonData = {
  104840. material: babylonMaterial,
  104841. meshes: [],
  104842. loaded: promise
  104843. };
  104844. material._babylonData[babylonDrawMode] = babylonData;
  104845. }
  104846. babylonData.meshes.push(babylonMesh);
  104847. assign(babylonData.material);
  104848. return babylonData.loaded;
  104849. });
  104850. };
  104851. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  104852. var promises = new Array();
  104853. // Ensure metallic workflow
  104854. babylonMaterial.metallic = 1;
  104855. babylonMaterial.roughness = 1;
  104856. var properties = material.pbrMetallicRoughness;
  104857. if (properties) {
  104858. if (properties.baseColorFactor) {
  104859. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  104860. babylonMaterial.alpha = properties.baseColorFactor[3];
  104861. }
  104862. else {
  104863. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104864. }
  104865. if (properties.baseColorTexture) {
  104866. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  104867. babylonMaterial.albedoTexture = texture;
  104868. }));
  104869. }
  104870. }
  104871. if (material.doubleSided) {
  104872. babylonMaterial.backFaceCulling = false;
  104873. babylonMaterial.twoSidedLighting = true;
  104874. }
  104875. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104876. return Promise.all(promises).then(function () { });
  104877. };
  104878. return KHR_materials_unlit;
  104879. }(GLTF2.GLTFLoaderExtension));
  104880. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  104881. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  104882. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104883. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104884. })(BABYLON || (BABYLON = {}));
  104885. //# sourceMappingURL=KHR_materials_unlit.js.map
  104886. "use strict";
  104887. var BABYLON;
  104888. (function (BABYLON) {
  104889. var GLTF2;
  104890. (function (GLTF2) {
  104891. var Extensions;
  104892. (function (Extensions) {
  104893. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  104894. var NAME = "KHR_lights";
  104895. var LightType;
  104896. (function (LightType) {
  104897. LightType["AMBIENT"] = "ambient";
  104898. LightType["DIRECTIONAL"] = "directional";
  104899. LightType["POINT"] = "point";
  104900. LightType["SPOT"] = "spot";
  104901. })(LightType || (LightType = {}));
  104902. var KHR_lights = /** @class */ (function (_super) {
  104903. __extends(KHR_lights, _super);
  104904. function KHR_lights() {
  104905. var _this = _super !== null && _super.apply(this, arguments) || this;
  104906. _this.name = NAME;
  104907. return _this;
  104908. }
  104909. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  104910. var _this = this;
  104911. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  104912. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  104913. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  104914. if (light.type !== LightType.AMBIENT) {
  104915. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  104916. }
  104917. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  104918. return promise;
  104919. });
  104920. };
  104921. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  104922. var _this = this;
  104923. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  104924. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  104925. var babylonLight;
  104926. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  104927. var name = node._babylonMesh.name;
  104928. switch (light.type) {
  104929. case LightType.AMBIENT: {
  104930. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  104931. }
  104932. case LightType.DIRECTIONAL: {
  104933. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  104934. break;
  104935. }
  104936. case LightType.POINT: {
  104937. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  104938. break;
  104939. }
  104940. case LightType.SPOT: {
  104941. var spotLight = light;
  104942. // TODO: support inner and outer cone angles
  104943. //const innerConeAngle = spotLight.innerConeAngle || 0;
  104944. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  104945. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  104946. break;
  104947. }
  104948. default: {
  104949. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  104950. }
  104951. }
  104952. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  104953. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  104954. babylonLight.parent = node._babylonMesh;
  104955. return promise;
  104956. });
  104957. };
  104958. Object.defineProperty(KHR_lights.prototype, "_lights", {
  104959. get: function () {
  104960. var extensions = this._loader._gltf.extensions;
  104961. if (!extensions || !extensions[this.name]) {
  104962. throw new Error("#/extensions: '" + this.name + "' not found");
  104963. }
  104964. var extension = extensions[this.name];
  104965. return extension.lights;
  104966. },
  104967. enumerable: true,
  104968. configurable: true
  104969. });
  104970. return KHR_lights;
  104971. }(GLTF2.GLTFLoaderExtension));
  104972. Extensions.KHR_lights = KHR_lights;
  104973. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  104974. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  104975. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104976. })(BABYLON || (BABYLON = {}));
  104977. //# sourceMappingURL=KHR_lights.js.map
  104978. return BABYLON;
  104979. });
  104980. /***/ }),
  104981. /* 35 */
  104982. /***/ (function(module, exports, __webpack_require__) {
  104983. /*!
  104984. * PEP v0.4.3 | https://github.com/jquery/PEP
  104985. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  104986. */
  104987. !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);
  104988. // define inherited MouseEvent properties
  104989. // skip bubbles and cancelable since they're set above in initEvent()
  104990. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  104991. // Spec requires that pointers without pressure specified use 0.5 for down
  104992. // state and 0 for up state.
  104993. var f=0;
  104994. // add x/y properties aliased to clientX/Y
  104995. // define the properties of the PointerEvent interface
  104996. 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(){
  104997. // only activate if this platform does not have pointer events
  104998. 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}})}/**
  104999. * This is the constructor for new PointerEvents.
  105000. *
  105001. * New Pointer Events must be given a type, and an optional dictionary of
  105002. * initialization properties.
  105003. *
  105004. * Due to certain platform requirements, events returned from the constructor
  105005. * identify as MouseEvents.
  105006. *
  105007. * @constructor
  105008. * @param {String} inType The type of the event to create.
  105009. * @param {Object} [inDict] An optional dictionary of initial event properties.
  105010. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  105011. */
  105012. 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},
  105013. // return value, key, map
  105014. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  105015. // MouseEvent
  105016. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  105017. // DOM Level 3
  105018. "buttons",
  105019. // PointerEvent
  105020. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  105021. // event instance
  105022. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  105023. // MouseEvent
  105024. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  105025. // DOM Level 3
  105026. 0,
  105027. // PointerEvent
  105028. 0,0,0,0,0,0,"",0,!1,
  105029. // event instance
  105030. "",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),
  105031. // Scope objects for native events.
  105032. // This exists for ease of testing.
  105033. eventSources:Object.create(null),eventSourceList:[],/**
  105034. * Add a new event source that will generate pointer events.
  105035. *
  105036. * `inSource` must contain an array of event names named `events`, and
  105037. * functions with the names specified in the `events` array.
  105038. * @param {string} name A name for the event source
  105039. * @param {Object} source A new source of platform events.
  105040. */
  105041. 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++)
  105042. // call eventsource register
  105043. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  105044. // call eventsource register
  105045. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  105046. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  105047. return!1}},
  105048. // EVENTS
  105049. 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)},
  105050. // LISTENER LOGIC
  105051. eventHandler:function(a){
  105052. // This is used to prevent multiple dispatch of pointerevents from
  105053. // platform events. This can happen when two elements in different scopes
  105054. // are set up to create pointer events, which is relevant to Shadow DOM.
  105055. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  105056. // set up event listeners
  105057. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  105058. // remove event listeners
  105059. 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)},
  105060. // EVENT CREATION AND TRACKING
  105061. /**
  105062. * Creates a new Event of type `inType`, based on the information in
  105063. * `inEvent`.
  105064. *
  105065. * @param {string} inType A string representing the type of event to create
  105066. * @param {Event} inEvent A platform event with a target
  105067. * @return {Event} A PointerEvent of type `inType`
  105068. */
  105069. makeEvent:function(b,c){
  105070. // relatedTarget must be null if pointer is captured
  105071. 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},
  105072. // make and dispatch an event in one call
  105073. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  105074. * Returns a snapshot of inEvent, with writable properties.
  105075. *
  105076. * @param {Event} inEvent An event that contains properties to copy.
  105077. * @return {Object} An object containing shallow copies of `inEvent`'s
  105078. * properties.
  105079. */
  105080. 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],
  105081. // Work around SVGInstanceElement shadow tree
  105082. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  105083. // This is the behavior implemented by Firefox.
  105084. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  105085. // keep the semantics of preventDefault
  105086. 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){
  105087. // Order of conditions due to document.contains() missing in IE.
  105088. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  105089. // Touch: Do not propagate if node is detached.
  105090. 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)}},/**
  105091. * Dispatches the event to its target.
  105092. *
  105093. * @param {Event} inEvent The event to be dispatched.
  105094. * @return {Boolean} True if an event handler returns true, false otherwise.
  105095. */
  105096. 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(
  105097. // is element a shadow host?
  105098. e=this.targetingShadow(f);e;){if(
  105099. // find the the element inside the shadow root
  105100. d=e.elementFromPoint(b,c)){
  105101. // shadowed element may contain a shadow root
  105102. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  105103. // check for older shadows
  105104. e=this.olderShadow(e)}
  105105. // light dom element is the target
  105106. return f}},owner:function(a){
  105107. // walk up until you hit the shadow root or document
  105108. for(var b=a;b.parentNode;)b=b.parentNode;
  105109. // the owner element is expected to be a Document or ShadowRoot
  105110. 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);
  105111. // if x, y is not in this root, fall back to document search
  105112. 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){
  105113. // Only watch scopes that can target find, as these are top-level.
  105114. // Otherwise we can see duplicate additions and removals that add noise.
  105115. //
  105116. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  105117. // a removal without an insertion when a node is redistributed among
  105118. // shadows. Since it all ends up correct in the document, watching only
  105119. // the document will yield the correct mutations to watch.
  105120. 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))},
  105121. // register all touch-action = none nodes on document load
  105122. 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){
  105123. // find children with touch-action
  105124. var b=x(a,this.findElements,this);
  105125. // flatten the list
  105126. // make sure the added nodes are accounted for
  105127. 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){}
  105128. // handler block for native mouse events
  105129. 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:[],
  105130. // collide with the global mouse listener
  105131. 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++){
  105132. // simulated mouse events will be swallowed near a primary touchend
  105133. 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);
  105134. // Update buttons state after possible out-of-document mouseup.
  105135. 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];
  105136. // Produces wrong state of buttons in Browsers without `buttons` support
  105137. // when a mouse button that was pressed outside the document is released
  105138. // inside and other buttons are still pressed down.
  105139. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  105140. // Support: Firefox <=44 only
  105141. // FF Ubuntu includes the lifted button in the `buttons` property on
  105142. // mouseup.
  105143. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  105144. 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),
  105145. // set touch-action on shadows as well
  105146. 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),
  105147. // remove touch-action from shadow
  105148. 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);
  105149. // simply update scrollType if listeners are already established
  105150. 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){
  105151. // set primary touch if there no pointers, or the only pointer is the mouse
  105152. (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,
  105153. // forward modifier keys
  105154. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  105155. // forward touch preventDefaults
  105156. 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))},
  105157. // For single axis scrollers, determines whether the element should emit
  105158. // pointer events or behave as a scroller
  105159. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  105160. // this element is a touch-action: none, should never scroll
  105161. b=!1;else if("XY"===c)
  105162. // this element should always scroll
  105163. 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]);
  105164. // if delta in the scroll axis > delta other axis, scroll instead of
  105165. // making events
  105166. 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},
  105167. // In some instances, a touchstart can happen without a touchend. This
  105168. // leaves the pointermap in a broken state.
  105169. // Therefore, on every touchstart, we remove the touches that did not fire a
  105170. // touchend event.
  105171. // To keep state globally consistent, we fire a
  105172. // pointercancel for this "abandoned" touch
  105173. vacuumTouches:function(a){var b=a.touches;
  105174. // pointermap.size should be < tl.length here, as the touchstart has not
  105175. // been processed yet.
  105176. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  105177. // Never remove pointerId == 1, which is mouse.
  105178. // Touch identifiers are 2 smaller than their pointerId, which is the
  105179. // index in pointermap.
  105180. 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);
  105181. // a finger drifted off the screen, ignore it
  105182. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  105183. // recover from retargeting by shadow
  105184. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  105185. // clean up case when finger leaves the screen
  105186. 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)},
  105187. // prevent synth mouse events from creating pointer events
  105188. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  105189. // only the primary finger will synth mouse events
  105190. if(this.isPrimaryTouch(c)){
  105191. // remember x/y of last touch
  105192. 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});
  105193. /***/ }),
  105194. /* 36 */
  105195. /***/ (function(module, exports, __webpack_require__) {
  105196. "use strict";
  105197. Object.defineProperty(exports, "__esModule", { value: true });
  105198. var defaultViewer_1 = __webpack_require__(5);
  105199. var mappers_1 = __webpack_require__(1);
  105200. /**
  105201. * Select all HTML tags on the page that match the selector and initialize a viewer
  105202. *
  105203. * @param selector the selector to initialize the viewer on (default is 'babylon')
  105204. */
  105205. function InitTags(selector) {
  105206. if (selector === void 0) { selector = 'babylon'; }
  105207. var elements = document.querySelectorAll(selector);
  105208. for (var i = 0; i < elements.length; ++i) {
  105209. var element = elements.item(i);
  105210. // get the html configuration
  105211. var configMapper = mappers_1.mapperManager.getMapper('dom');
  105212. var config = configMapper.map(element);
  105213. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  105214. }
  105215. }
  105216. exports.InitTags = InitTags;
  105217. /***/ })
  105218. /******/ ]);
  105219. return BabylonViewer;
  105220. });